I have a Java application that uses swing. I have found a way to catch all uncaught exception in an application (see below). I would like to log a message, show a dialog with a message for the user and kill the application. The problem is, what I’m trying to catch are some swing exceptions. Trying to show a dialog after the exception is caught in the UncaughtExceptionHandler is impossible since the Swing thread is stopped. Is there any way to then show a dialog? Creating a new swing thread or something like this?
Thanks!
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
boolean alreadyCaught = false;
public void uncaughtException(Thread t, Throwable e) {
if (alreadyCaught)
return;
alreadyCaught = true;
e.printStackTrace();
//show Dialog
}
});
It is perfectly possible to show a dialog from the default uncaught exception handler. One of our products is using this mechanism for the last 5 years without any problems.
We have a workaround for the problem when the EDT is being replaced due to the exception killing the current EDT. Instead of using the regular
SwingUtilities#invokeLaterto show the dialog, we useThis allows the EDT to be replaced by a new one, and runs the
Runnableon the newly created EDT.