Can we have try/catch in a static block in a class?
hi All
i have a question about put a try/catch block in a static block in a class to catch exceptions that maybe thrown from using System.xxxx(). in my custom class, i have a static block to initialize some variables using System.xxx(). in case of any error/exception, i need to be able to catch it and let the caller know about it. i tried to put a try/catch block in the static block, and tried to rethrow the exception. but it is not allowed, how would i handle situation like this? thanks for your help and advise in advance.
You could just swallow the exception inside try/catch
block, and instead of throwing it out, just set a
static variable to allow checking from outside
whether the initialization succeeded, or check within
the constructor / methods of this class for
successful initialization, and throw the exception
then. You could even save that exception in a static
variable for later.Ouch, ouch, you're hurting my brain. This would allow someone to ignore a (presumably) fatal error. Throw a RuntimeException as indicated. You can wrap a checked exception in an unchecked one if need be.
Similar Messages
-
Does Labview have Try Catch exception handling?
1) Does Labview have Try Catch functions, exception handling?
2) Can Labview access a file or download a file using http or https?
3) How can labview read data from an ex ternal server http or https?
This is in labview 2009 or 2011Hi E,
1. you can chain together your VIs with the error wires, such that if an error occurs in one of them, none of the following VIs will execute. That's like throwing an exception - it interrupts the execution chain. You then "catch" that exception by putting an error handler wherever necessary, but not necessarily in every single VI.Hope You wouldn't put try..catch inside every single .NET function, instead you handle the exception at the level at which is most appropriate. Same thing can be done in LabVIEW.
Also see this.
2. The attached example downloads a picture with http "GET" command.
Dilbert.Main_LV71.vi 160 KB
3.see this thread:
http://forums.ni.com/t5/LabVIEW/Read-a-text-file-from-Labview-web-server-http/td-p/267434
Yes!!The same thing pointed out by nijims.
Thanks as kudos only -
i am wondering how many devices can be synced to a desktop version of Firefox Home? i have a teacher i am working with who has a classroom set of iPod Touches (5th grade). Firefox Home would be a nice way to get all of the students onto certain websites easily . . . potentially. is this possible?
I don't believe there is a limit but I've never tried more than 4 or 5 devices.
-
Class design question: Can you have an enum of class objects?
Hi, thank you for reading this post!
We all know that an enum represents a set of constants, but sometimes a class has a restricted set of values as
well. My question is can we have an enum of objects.
Example:
We have a class named Coin
A coin with a monetary value.
public class Coin implements Measurable
private double value;
private String name;
public Coin(double aValue, String aName)
value = aValue;
name = aName;
public double getValue()
return value;
public String getName()
return name;
public double getMeasure()
return value;
}We all know that a coin has a set of values "Dollar" = 1.00, "Quarter" = 0.25, "Dime" = 0.10, "Nickel" = 0.05, and
"Penny" = 0.01.
Can we have an enum of Coins with Coin as a class at the same time?
If yes, how do we do this?
Thank you in advance for your help!
EricMaybe you want something like this:
public enum Coin implements Measurable {
DOLLAR(1.00, "Dollar"),
QUARTER(0.25, "Quarter"),
DIME(0.10, "Dime"),
NICKEL(0.05, "Nickel"),
PENNY(0.01, "Penny")
private double value;
private String name;
Coin(double aValue, String aName)
value = aValue;
name = aName;
public double getValue()
return value;
public String getName()
return name;
public double getMeasure()
return value;
} -
Exception in static block + re-instantiating
Hello All,
I have got a number of unit tests and one that is running is causing an exception in a static block of a class which is expected. It throws an ExceptionInInitializerError which I catch in the unit test.
But then another test is running using the same class and this time it should pass and create an instance of the same class as before.
But instead I receive a java.lang.NoClassDefFoundError with no class name. Why? Can't I instantiate a class again once the initialisation had failed?
Regards
JonasIt's part of the VM Specification.
See [2.17.5 Detailed Initialization Procedure|http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#24237]
The first time,
10. Otherwise, the initializers must have completed abruptly by throwing some exception E. If the class of E is not Error or one of its subclasses, then create a new instance of the class ExceptionInInitializerError, with E as the argument, and use this object in place of E in the following step. But if a new instance of ExceptionInInitializerError cannot be created because an OutOfMemoryError occurs, then instead use an OutOfMemoryError object in place of E in the following step.After that,
5. If the Class object is in an erroneous state, then initialization is not possible. Release the lock on the Class object and throw a NoClassDefFoundError. -
Hi,
I have been hunting down a NullPointerException for half a day to come to
the following conclusion.
My constructor calls a method which uses static variables. Since an intance
of my class is created in the static block when the class is loaded, those
statics are probably not fully initialized yet and the constructor called
from the static block has those null pointer problems.
I've considered moving the initialization of the static variables from the
declaration to the static block. But your code is inserted BEFORE any other
code. Therefore not solving my problem.
Two questions:
1) what would be a solution to my problem? How can I make sure my static
variables are initialized before the enhancer generated code in the static
block calls my constructor? Short of decompiling, changing the code and
recompiling.
2) Why is the enhancing code inserted at the beginning of the static block
and not at the end? The enhancements would be more transparent that way if
the static variables are initialized in the static block.
Thanks,
EricHi Eric,
JDO calls the no-args constructor. Your application should regard this constructor as belonging
primarily to JDO. For example, you would not want to initialize persistent fields to nondefault
values since that effort is wasted by JDO's later initilization to persistent values. Typically all
you want to initialize in the no-args constructor are the transactional and unmanaged fields. This
rule means that you need initialization after construction if your application uses the no-args
constructor and wants persistent fields initialized. On the other hand, if your application really
uses constructors with arguments, and you're initializing persistent fields in the no-args
constructor either unintentionally through field initializers or intentionally as a matter of
consistency, you will find treating the no-args constructor differently helpful.
On the other hand, if Kodo puts its static initializer code first as you report, then it is a bug.
Spec Section 20.16: "The generated static initialization code is placed after any user-defined
static initialization code."
David Ezzio
Eric Borremans wrote:
>
Hi,
I have been hunting down a NullPointerException for half a day to come to
the following conclusion.
My constructor calls a method which uses static variables. Since an intance
of my class is created in the static block when the class is loaded, those
statics are probably not fully initialized yet and the constructor called
from the static block has those null pointer problems.
I've considered moving the initialization of the static variables from the
declaration to the static block. But your code is inserted BEFORE any other
code. Therefore not solving my problem.
Two questions:
1) what would be a solution to my problem? How can I make sure my static
variables are initialized before the enhancer generated code in the static
block calls my constructor? Short of decompiling, changing the code and
recompiling.
2) Why is the enhancing code inserted at the beginning of the static block
and not at the end? The enhancements would be more transparent that way if
the static variables are initialized in the static block.
Thanks,
Eric -
Use of functions in static block
Hello,
I have this app containing a static {} block. The reason it's there is to 1) provide a splash screen 2) have input dialog to process input string and check if it's valid in order to load app or not.
In pseudocode it's like this:
1 - get input string with showInputDialog()
2 - check for the input string validity (a valid string is with prefix A-, C- or S-)
3 - if string is valid, load the app
4 - if string is not valid, proceed to step 1.
As you may already see, there is going to be a lot of code (with if-else statements) to check for A-, C- and S- prefixed because I am using indexOf() function which takes only one parameter.
I am considering a way to somehow check recursively, but for this I think I'll need a function to call indexOf() with A-, C-, S- and assess validity for each case.
My question is, is there a way in the static block to have a function? Or can somebody please recommend an efficient approach to checking a string validity with different possibilities inside a static block as in my case, to avoid lots of if-else statements?
P.S. My apologies for initially posting this thread in wrong section.
Thank you!
Victor.DrClap wrote:
What's a function? And why are you particularly concerned about doing those things in a static initializer as opposed to in some other place?Hi,
Sorry, I'm still thinking c++. I meant method. Something like of the form:
static
boolean valid = false;
while string is not valid
stringfrominput = showInputDialog();
//determine if string is valid
valid = checkvalid(stringfrominput)
//if possible to have
boolean checkvalid(stringfrominput)
recursively process stringfrom input based on A-, S-, or C- prefixes
return boolean value
}I have a jar app. It is Windows-based and runs as a TrayIcon application. If I include this process when class is loaded, this means that the app will be loaded with all its features. But I need to make sure that the app's features will be loaded only if certain conditions are met.
I am not sure how else to approach this requirement without using static {} block.
Thank you,
Victor. -
public class SubClass extends SuperClass {
static {
System.out.println("Sub class being called");
SuperClass.setS("TREX");
public class SuperClass {
protected static String s;
static {
System.out.println("Super being called ");
static public setS(String t) { s= t; }
static public String getS() { return s; }
public static void main(String[] args) {
System.out.println(SubClass.getS());
The above prints
"Super being called"
null
Why is "Sub class being called " not printed? It looks like
the subclass static block never gets called.?hi
may be i did not something catch right concerning static blocks and inheritence
(jdk1.5x)
please have a look at the following example.
1. static block in subclass is only executed if the static vars are not defined final. why is this?
2. why does not any subclass has its "own" hashtable colors?
thanks
hanspeter
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
import java.util.Hashtable;
abstract class ParentStaticBlock {
static final Hashtable<Integer, String> colors = new Hashtable<Integer, String>();
static void putColor(int colNumber, String colName) {
colors.put(colNumber, colName );
static String getColorNameFor(int colNumber) {
return colors.get(colNumber);
final class Child1StaticBlock extends ParentStaticBlock {
public final static int ROT = 0x00000D;
public final static int GELB = 0x00000E;
static {
System.out.println(" hello, here static block of Child1StaticBlock...");
putColor(ROT, "ROT");
putColor(GELB, "GELB");
final class Child2StaticBlock extends ParentStaticBlock {
public /*final*/ static int GRUEN = 0x00000A;
public /*final*/ static int BLAU = 0x00000B;
static {
System.out.println(" hello, here static block of Child2StaticBlock...");
putColor(GRUEN, "GR�N");
putColor(BLAU, "BLAU");
public class TestChildStaticBlock {
* @param args
public static void main(String[] args) {
int colNo;
String colBez;
System.out.println("Static elements class Child1StaticBlock ->");
colNo = Child1StaticBlock.GELB ;
colBez = Child1StaticBlock.getColorNameFor(colNo);
System.out.println("color yellow has number >" + colNo + "< and label >" + colBez + "<");
System.out.println("");
System.out.println("Static elements class Child2StaticBlock ->");
colNo = Child2StaticBlock.BLAU ;
colBez = Child2StaticBlock.getColorNameFor(colNo);
System.out.println("color blue has number >" + colNo + "< and label >" + colBez + "<");
System.out.println("");
System.out.println("contents of hashtable(s) ->");
System.out.println("ParentStaticBlock.colors:" + ParentStaticBlock.colors);
System.out.println("Child1StaticBlock.colors:" + Child1StaticBlock.colors);
System.out.println("Child2StaticBlock.colors:" + Child2StaticBlock.colors); -
Can't find class because of try catch block ?!
Hello,
I'm using the JNI to use a java library from my c++ code.
JNI can't find the "Comverse10" class below, but when i put the try catch block in createMessage in comment, FindClass succeeds ?!
Unfortunatly i need the code inside the try block ;-)
I tried a few things, but none of them worked:
- let createMessage throw the exception (public void createMessage throws ElementAlreadyExistsException ), so there isn't a try catch block in createMessage => result: the same
- make a "wrapper" class Comverse that has a Comverse10 object as attribute and just calls the corresponding Comverse10.function. Result: Comvers could be found, but not constructed (NewObject failed).
Can someone tell me what is going on ?!
Thank you,
Pieter.
//Comverse10 class
public class Comverse10 {
MultimediaMessage message;
/** Creates a new instance of Comverse10 */
public Comverse10() {
public void createMessage() {
TextMediaElement text1 = new TextMediaElement("Pieter");
text1.setColor(Color.blue);
SimpleSlide slide1 = new SimpleSlide();
//if i put this try catch block in comment, it works ?!
try{
slide1.add(text1);
catch(com.comverse.mms.mmspade.api.ElementAlreadyExistsException e){}
MessageContent content = new MessageContent();
content.addSlide(slide1);
this.message = new MultimediaMessage();
message.setContent(content);
message.setSubject("Mijn subjectje");
for those of you who are intersted: here's my C++ code:
//creation of JVM
HRESULT Java::CreateJavaVMdll()
HRESULT HRv = S_OK;
char classpath[1024];
jint res;
if(blog) this->oDebugLog->Printf("CreateJavaVMdll()");
strcpy(classpath,"-Djava.class.path="); /*This tells jvm that it is getting the class path*/
strcat(classpath,getenv("PATH"));
strcat(classpath,";D:\\Projects\\RingRing\\MMSComposer;C:\\Progra~1\\j2sdk1~1.1_0\\lib"); //;C:\\Comverse\\MMS_SDK\\SDK\\lib\\mail.jar;C:\\Comverse\\MMS_SDK\\SDK\\lib\\activation.jar;C:\\Comverse\\MMS_SDK\\SDK\\lib\\mmspade.jar
//------Set Options for virtual machine
options[0].optionString = "-Djava.compiler=NONE"; //JIT compiler
options[1].optionString = classpath; //CLASSPATH
//------Set argument structure components
vm_args.options = options;
vm_args.nOptions = 2;
vm_args.ignoreUnrecognized = JNI_TRUE;
vm_args.version = JNI_VERSION_1_4;
/* Win32 version */
HINSTANCE hVM = LoadLibrary("C:\\Program Files\\j2sdk1.4.1_01\\jre\\bin\\client\\jvm.dll");
if (hVM == NULL){
if(blog) oDebugLog->Printf("Can't load jvm.dll");
return E_FAIL;
if(blog) oDebugLog->Printf("jvm.dll loaded\n");
LPFNDLLFUNC1 func = (LPFNDLLFUNC1)GetProcAddress(hVM, "JNI_CreateJavaVM");
if(!func){
if(blog) oDebugLog->Printf("Can't get ProcAddress of JNI_CreateJavaVM");
FreeLibrary(hVM); hVM = NULL;
return E_FAIL;
if(blog) oDebugLog->Printf("ProcAddress found");
res = func(&jvm,(void**)&env,&vm_args);
if (res < 0) {
if(blog) oDebugLog->Printf("Can't create JVM with JNI_CreateJavaVM %d\n",res);
return E_FAIL;
if(blog) oDebugLog->Printf("JVM created");
return HRv;
//finding Comverse10 class:
HRESULT CALLAS MMSComposer::InitializeJNI(void)
HRESULT HRv=E_FAIL;
DWORD T=0;
try
if(blog) oDebugLog->Printf("\nInitializeJNI()");
bJVM = FALSE;
jni = new Java(oDebugLog);
if(jni->CreateJavaVMdll()!=S_OK){
if(blog) oDebugLog->Printf("CreateJavaVMdll() failed");
return HRv;
jclass jcls = jni->env->FindClass("Comverse10");
if (jcls == 0) {
if(blog) oDebugLog->Printf("Can't find Comverse10 class");
jclass jcls2 = jni->env->FindClass("test");
if (jcls2 == 0) {
if(blog) oDebugLog->Printf("Can't find test class");
return HRv;
if(blog) oDebugLog->Printf("test class found %08x",jcls2);
return HRv;
if(blog) oDebugLog->Printf("Comverse10 class found %08x",jcls);
jmethodID mid = jni->env->GetMethodID(jcls , "<init>", "()V");
if (mid == 0) {
if(blog) oDebugLog->Printf("Can't find Comverse10() constructor");
return HRv;
if(blog) oDebugLog->Printf("Comverse10() constructor found");
jobject jobj = jni->env->NewObject(jcls,mid);
if(jobj==0)
if(blog) oDebugLog->Printf("Can't construct a Comverse10 object");
return HRv;
if(blog) oDebugLog->Printf("Comverse10 object constucted");
//Create Global reference, so java garbage collector won't delete it
jni->jobj_comv = jni->env->NewGlobalRef(jobj);
if(jni->jobj_comv==0)
if(blog) oDebugLog->Printf("Can't create global reference to Comverse10 object");
return HRv;
if(blog) oDebugLog->Printf("global reference to Comverse10 object %08x created",jni->jobj_comv);
bJVM=TRUE;
HRv=S_OK;
} catch( IDB * bgError ) { throw bgError->ErrorTrace("InitializeJNI::~InitializeJNI",HRv, 0, T); }
catch(...) { throw IDB::NewErrorTrace("InitializeJNI::~InitializeJNI",HRv, 0, T ); }
return HRv;>
I would guess that the real problem is that that the
exception you are catching is not in the class path
that you are defining.Thanks jschell, that was indeed the case.
I don't have the docs, but I would guess that
FindClass() only returns null if an exception is
thrown. And you are not checking for the exception.
Which would tell you the problem.Ok, i'll remember that. But what with exceptions thrown in my java code, the documents say
// jthrowable ExceptionOccurred(JNIEnv *env);
// Determines if an exception is being thrown. The exception stays being thrown until either the native code calls ExceptionClear(), or the Java code handles the exception
so, what if the java code throws an exception and catches it, will i be able to see that in my c++ code with ExceptionOccurred ?
or
should the java method be declared to throw the exception (and not catch it inside the method)
Again, thank you for your help, it's greatly appreciated ! -
How can I make the background one solid color? It is too difficult and noticeable when I use the retouch button and try to erase all the creases in my backdrop. So, how can I have just a solid white background?
When talking about a specific image posting the image may be useful.
One can use a Layer Mask and add a white Layer underneath. -
I just got an iPhone 5S, now when I try to use my old iPad the apps won't work because they are syncing with my new phone. Can I have the same account for an old iPad and a new iPhone?
Connect your iPad to iTunes on the computer you usually Sync with and “ Check for Updates “...
If an Update Appears Install it... if not... you are up to date for your particular Device...
See the Using iTunes Section Here...
How to update your iPhone, iPad, or iPod touch
Make sure you have the Latest Version of iTunes (v11) Installed on your computer
iTunes free download from www.itunes.com/download -
I used to have my old work e mail address as my Apple ID but have now changed it to my new one, had all of the verification e mails and everything. However, when I try to download or update my apps, my original ID comes up and I can't log in. Can't remember my original passowrd and can't have a reminder sent to the original e mail as it no longer exists..... help!
Any content is tied to the account that you used to buy/download it - so if you created a new account as opposed to updating the existing one, then you will need to use the old account to download updates to its apps. Can you not update your old account so as to have a new email address on it (e.g. via this page) ?
-
After my iphone4S update to 7.0.6, it have a problem that keep searching network then no service show on display. Can't call. I have try check sim card, reset network settings, and restore my iphone. Still not working at all. Need help please.Urgent.TQ
Izit software or hardware? Confuse:(
Only can use wifi now.
Any way thanks guys for ur suggestion:) amishcake and simes -
please help. my pc is a hp with windows vista 32 bit. I can't install itunes 10,5. I have try to remove my old itunes and reinstall but it didn't help. I have install itunes 9.1.1 but the itunes library can't be read because it is on a new itunes. I hope someone can help. I'm lost.
Deauthorize all of your computers and authorize the computers you use.
http://support.apple.com/en-us/HT6283
A new Mac comes with 90 days of free tech support from AppleCare.
AppleCare: 1-800-275-2273
Best. -
Problem. Alla my tools and panels are hidden, can´t find them. Have try Windows>menyer....... and checked. all is ok.
Press the Tab key, it shows/hides panels.
Or Window > Workspace > Reset or use a different workspace.
Gene
Maybe you are looking for
-
The exception Privileged instruction.
Hello, I builded a dll which communicates with TDC card. But when I call dll from labview. It gives me the error The exception Privileged instruction. (0xc0000096) occured in the application at location 0x02e6121c. I have installed giveio driver. I a
-
Multiple pages in measurement mode when using DIAdem
Is it possible to have multiple visualisation pages availble when obtaining measurements and if so can you "switch between the pages?
-
Fail to lookup the local EJB by JNDI in Managed Server
Hi all, I currently in a deep problem, and can't figure out the cause of it. It just annoying me for week. In my app, I have binded to the local ejb to JNDI (let's say "ejb/CustomerLocal"), then the client lookup the Local EJB by the following code.
-
I provide my customers an ethernet port off my PE (ie: FastEthernet0/0 on PE from configuration below). They can connect whatever they want into the port. Most times it's simply a PC. The only thing they expect to get off that port is Internet acc
-
Create an Application Object schedule from command line?
Hi everyone - long-time lurker, first-time poster here. Is there a way create an availability schedule for an Application Object via a command line (or any other programmatic method)? The utilities I've obtained from Cool Solutions are great for repl