You can do this, but you need to exit the static block by throwing an exception - you can rebuild the exception that was caught or a new one. Usually this exception should be a RuntimeException . You really shouldn't catch a general Exception , but a more specific exception (s) that can be thrown from your try block. Finally, if the static initializer throws an exception, it will render the class unusable during this particular run, because the JVM will try to initialize your class only once. Subsequent attempts to use this class will result in another exception, such as NoClassDefFoundError .
So, in order to work, your initializer must read something like this:
static { try { ... } catch (Exception e) { e.PrintStackTrace(); throw new InitializationFailedException("Could not init class.", e); } }
Assuming InitializationFailedException is a custom RuntimeException , but you can use an existing one.
Kevin Brock Feb 26 '10 at 7:02 2010-02-26 07:02
source share