开发者

Java (SWT/JFace)- handling all exceptions within Runnable

开发者 https://www.devze.com 2023-04-12 15:40 出处:网络
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

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 Exceptions. 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 Errors. Try catch (Throwable e) instead of catch (Exception e).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号