Java (SWT/JFace)- handling all exceptions within Runnable
I have an SWT/JFace application that uses the Realm (not sure of the concept) class to run the main program as a thread. I'm trying to catch any uncaught exceptions using a try/catch block around my main code:
public static void main(String args[]) {
// ref: http://forums.instantiations.com/viewtopic.php?f=1&t=1583
Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
public void run() {
try {
PropertyConfigurator开发者_如何学Go.configure("log4j.properties");
MainWindow window = new MainWindow();
window.setBlockOnOpen(true);
window.open();
Display.getCurrent().dispose();
} catch (Exception e) {
MessageDialog.openError(null, "Error", "Error occurred: " + e.getMessage());
logger.error("Error!!!", e);
e.printStackTrace();
}
}
});
}
The errors get thrown back to the window.open()
line fine, but are then passed on to Realm, so the catch
block is never reached. Here's the end of a stack trace:
at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
at org.eclipse.jface.window.Window.open(Window.java:801)
at com.ism.MainWindow$1.run(MainWindow.java:210) <-- "window.open();"
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at com.ism.MainWindow.main(MainWindow.java:204) <-- "Realm.runWithDefault....."
Tried putting a try/catch around Realm.runWithDefault
but that didn't work either.
How do I capture all of the exceptions in this case?
Some UI runnable is throwing an Exception
in the display event loop. You need to set up a different event loop exception handler. (The default simply prints the exception to the console.)
For example:
Window.setExceptionHandler(new Window.IExceptionHandler() {
public void handleException(Throwable error) {
MessageDialog.openError(null, "Error", "Error: " + error.getMessage());
}
});
Or, of course, you could rethrow and catch at your top-level like in your example.
Note, however, that this is a static method on Window
, so this exception handler is application-wide.
Your catch
block is only catching Exception
s. However, you don't say what exceptions are being thrown and not being caught. So, in the absence of any further information, I'm going to guess that these exceptions are in fact Error
s. Try catch (Throwable e)
instead of catch (Exception e)
.
精彩评论