In Java, we handle exceptions using try catch blocks. I know that I can write a try catch block like the one below to catch any exception thrown in a method.
try {
// do something
}
catch (Throwable t) {
}
But is there any way in Java which allows me to get a specific method called when an exception happens, instead of writing a catch-all method like the one above?
Specifically, I would like to show a user friendly message in my Swing application when an exception is thrown (which is not handled by my application logic).
Thanks.
By default, the JVM handles uncaught exceptions by printing the stack-trace to System.err stream. Java allows us to customize this behavior by providing our own routine which implements
Thread.UncaughtExceptionHandlerinterface.Take a look at this blog article which I wrote sometime back which explains this in detail ( http://blog.yohanliyanage.com/2010/09/know-the-jvm-1-uncaught-exception-handler/ ).
In summary, all you have to do is write your custom logic as below :
And set it using any of the three options I have described in the above link. For example, you could do the following to set the default handler for the entire JVM (so any uncaught exception thrown will be handled by this handler).