Originally posted by P. Ingle: I am loading native library in static block - which, if fails, shuts JVM all together. I would like to have some graceful way of handling this situation.
if the failure really should exit the entire program, then you don't need to throw an exception in order to achieve this — you can just print an error message and System.exit() to get out. in fact, that would likely be more graceful than leaving the user with a stack dump from an unhandled exception on the screen.
IIRC, you can put the throws clause after the static keyword:
Also note that it is usually considered a good practice to throw (or catch) specific Exception subclasses rather than just throwing (or catching) Exception itself. This is primarily because when you catch Exception, this also includes Runtime errors that usually indicate a programming error such as NullPointerException.
No, you can't put a throws clause after the static keyword.
What you need to do is throw an ExceptionInInitializerError. From the JavaDocs:
Signals that an unexpected exception has occurred in a static initializer. An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.
Peter Korsten wrote:What you need to do is throw an ExceptionInInitializerError.
Well, we don't quite need to, in the sense that any other exception we throw will be caught by the JVM, wrapped in an ExceptionInInitializerError, and then rethrown. So if we want to throw some other (unchecked) exception with more specific information about what went wrong, that works too. There are pros and cons to each approach, but they both end up with the result that the class is subsequently unusable, and letting the JVM exit is often the best strategy.