Is it possible to throw exceptions when a class is loaded ??? For example, I would like to have a static initialiser to my class where i perform some init stuff and if an exception occurs over here, I want to abort the class loading itself, forget about instantiating it... , and throw an exception at this point. AFAIK, i cant throw an exception from a static intialiser right?? Regards.
You can't throw a checked exception, but you can throw an unchecked one -- i.e., a RuntimeException. This will result in the JVM throwing an ExceptionInInitializerError which, depending on the circumstances, you may be able to catch somewhere else in your code.
Originally posted by Ernest Friedman-Hill: You can't throw a checked exception, but you can throw an unchecked one -- i.e., a RuntimeException. This will result in the JVM throwing an ExceptionInInitializerError which, depending on the circumstances, you may be able to catch somewhere else in your code.
thanx for the reply. I think I better throw ExceptionInInitializerError itself. This makes more sense in my code that an exception has occured during static initialisation. Thanx, SHankar. [ November 16, 2003: Message edited by: shankar vembu ] [ November 16, 2003: Message edited by: shankar vembu ]
I've got a problem which is related to this. I have a plugin which is loaded from my main app. The plugin is simply a class which implements an interface. The plugin has inner classes and they appear to be the problem. In pseudo code I have the following -
The problem is that when I dynamically load the class, I get an InstantiationException for class MyPlugin.TextFieldHandler. I thought that exception was only thrown when an instance of an Abstract class or Interface was trying to be created? Any ideas? Regards - Aaron R>
author and iconoclast
There's nothing intrinsically wrong with your scenario, and I can't think of an obvious way that this problem could come up. You can actually get an InstantiationException if you try to create an instance of a non-static inner class directly using Class.forName(), because it won't have a proper enclosing instance -- but it doesn't look like that's the problem. You might try deleting all the .class files you can find and recompiling everything. If you still have the problem, then we probably need to see more code.
Joined: Sep 10, 2002
I figured out what the problem was! I was loading classes without checking to see if the class was an innerclass or a top level one. I'm going to start a new thread related to it, as it I don't want this one to go off topic too much! Regards!