1. How to set the program in a way that any swing RuntimeException stop the whole application?
I guess I must start saying that
java.lang.RuntimeException is used for programming errors. Therefore, instead of trying to handle this kind of exception, you must fix the code for this kind of exceptions never happen.
For instance, an ArithmeticException happens when you try to perform a division by zero. You must not handle this exception, because this is never expected to happen, you must correct this kind of bugs.
Now, that said, what you want to do can be carried out in two different ways, with slight differences.
The first procedure is barely documented strategy. You start by defining a class like this:
Then, before the
Event Dispatch Thread (The Swing main thread) is started you initialize a system property like this:
Make sure that the name of the class ErrorHandler is the fully quallified name of the class (i.e. com.javaranch.ErrorHandler), not just its cannonical name (ErrorHandler).
And voila! Magically this method will be called every time an uncaught exception happens in Swing (the
Event Dispatch Thread).
You see how this mechanism works reading the source code in the
java.awt.EventDispatchThread which is not public class and that is why you will not see its documentation in the javadoc API.
The second mechanism you can use is only available in JDK 1.5. since the new API incorporates a new method:
Thread.setUncaughtExceptionHandler().
All you have to do is to implement Thread.UncaughtExceptionHandler and assign an instance of this implementation to the
Event Dispatch Thread.
For example (this code must run within the
EventDispathThread):
2. How can I set an action before the stop of the whole application generate by the first method? (like a popup alert containing the error message and any release of lock, etc.)
Evidently, in either approach you could display a dialog box within the event handler. The only problem is that by doing this you could be creating a new
EventDispatchThread. The first approach will continue to handle exception, in the second approach you would have to register again the
UncaughtExceptionHandler.
Another approach for this could be to use the
Runtime.addShutdownHook(Thread t) which would give you the chance to execute some code before the
exit() has had a chance to finish the JVM.
All this seems to me like too much work just to handle an exception that should have never happened in the first place.
[ October 18, 2006: Message edited by: Edwin Dalorzo ]