views:

104

answers:

2

For desktop apps, it's useful to see the stacktrace on the GUI when the program crashes. I implemented this in Java by replacing System.err with my own error handler, which redirects all error messages to a GUI component and a text file.

The problem: Quite a few libraries out there (e.g. Apache POI) don't just write to System.err when a crash occurs, they also output simple warning messages. This causes the crash window to pop up unnecessarily. So my question is, does anybody know how to (1) show the stacktrace when the program crashes, while (2) not showing it in case of warning messages?

[Edit] My GUI is written in SWT.

+2  A: 

You can install own exception handlers. One technique for Swing is explained here: http://ruben42.wordpress.com/2009/03/30/catching-all-runtime-exceptions-in-swing/. Eric Burke also has nice article on this topic. Another general technique is using Thread.setDefaultUncaughtExceptionHandler, which is called when thread dies due to exception (according to comments in the first referenced article, Swing thread doesn't die, so setting uncaught exception handler doesn't work for Swing, but Eric's article uses this technique).

Your exception handler can then display error, log it, or do anything you want, without caring about other code using standard output/error streams.

Peter Štibraný
+2  A: 

I think you're approaching the problem from the wrong angle. You should be popping up a dialog when there are exceptions, not just when there is output to System.err. System.err is more like a logging utility.

For all checked exceptions, you should handle them case by case in your code. Either pop up a dialog, log them, or ignore them (but in that case, be sure that it's really safe to do so)

To catch any remaining unchecked exceptions, you can do something like this: http://www.javaspecialists.eu/archive/Issue081.html, to make sure that you're getting those.

amarillion