exception in static initializer causes program to hang
I have a GUI application. In my main class I have a method (called createAndShow()
) to initialize all my GUI classes. Inside each GUI class, I have static initializer
to read properties files(resource bundles or configuration files). If a file or entry is missing or value is wrong, I catch the exception and then throws a MissingResourceException
to upper level on 开发者_如何学Pythonpurpose. In my createAndShow()
method of the main class, I put a try-catch to catch Exception
. But somehow JVM refuse to get there. Whenever a file is missing, that MissingResourceException
is thrown and then the application just hang. I expected the createAndShow()
method will catch that exception and exit gracefully. Is there anything special for exceptions throws from the static initializer?
I am using XP and java 1.6.
Static initializers are invoked by the class loader not by any user code.
You will not be able to capture those exceptions, and since the classes you need are not able to be loaded, your application will crash.
My recommendation would be to do a Configuration singleton class, you could use What is an efficient way to implement a singleton pattern in Java?. Create an init()
or load()
method in that class which will be able to throw the exceptions that can be catched in your createAndShow()
method.
The static initializer block will be called when the class is loaded. If it throws an exception, the class will not be loaded and you will end up with a NoClassDefFoundException.
You should simply log errors and move on when you have missing resources. Or, you don't do the loading in static initializer blocks, but instead do it in a separate class whose sole purpose is to load these resource bundles.
Exceptions thrown in static initializer blocks result in the class not being loaded, which means that your calling class that uses the class can't be loaded either, unless you are using some very careful defensive coding techniques.
精彩评论