Tuesday, April 28, 2009

Catching uncaught exceptions in Java

This month looks quite javaized!
So here is another thing I came up with, regarding uncaught exceptions which usually end the application totally unexpectedly. I wouldn't mind about that, but I felt that the user should be notified with a minimum-sense message and some technical info so that he/she can send it over to the developers.
So here it is a 'BodyGuard' class that does the job by using a callback present in the Thread class.


package bodyguard;

public class BodyGuard implements Thread.UncaughtExceptionHandler
{
static private BodyGuard bGuard;

static public void registerGuard() {
bGuard = new BodyGuard();
Thread.setDefaultUncaughtExceptionHandler(bGuard);
}

public void uncaughtException( Thread thread, Throwable e )
{
java.io.StringWriter sW = new java.io.StringWriter();
e.printStackTrace( new java.io.PrintWriter(sW));

String s = "A fatal error was detected during execution: \n" +
"Thread: " + thread.getName() + "\n" +
"Exception: " + sW.toString() + "\n" +
"The application will be closed now.";

showFatalErr(s);
}

private void showFatalErr( String err )
{
//JOptionPane.showMessageDialog(null, err,"Error", JOptionPane.ERROR_MESSAGE);
BodyGuardDialog dlg = new BodyGuardDialog(null, true, err);
dlg.setLocationRelativeTo(null);
dlg.setVisible(true);

System.exit(-1); //exit n ow
}
}

BodyGuardDialog is another class derived from JDialog that shows the corresponding error message and lets the user copy the error to the clipboard.
In order to register this handler one just has to call bodyguard.BodyGuard.registerGuard() when starting up (ie: static void main()).
This class will catch uncaught exceptions from all threads, displaying the thread's name where the exception was thrown.
_

No comments:

Post a Comment