Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling exceptions in Swing GUI

I'm not sure about how manage exceptions in GUI; my goal is to let the user know if something goes wrong showing an intelligible message.

I'm thinking to do something like this:

// I'm inside an actionPerformed() method
try {
    // do whatever I have to do here
} catch (KnownBusinessException1 e) {
    // inform the user and do something;
    // most times simply inform the user that it wasn't possible to complete the
    // operation and remain in the same window instead of moving forward.
} catch (KnownBusinessException2 e) {
    // just as above
} catch (KnownDataAccessException1 e) {
    // just as above
} catch (KnownDataAccessException2 e) {
    // just as above
} catch (RuntimeException e) { // I want to catch any other unexpected exception,
// maybe NPE or unchecked IllegalArgumentExceptions and so on
    // something went wrong, I don't know where nor how but I will surely inform the user
}

Now: If in the try block there are checked exceptions to catch, would it be better to nest a try/catch or to catch these checked exceptions after catching RuntimeException? (it probably depends, I don't even know if this is going to happen btw)

Another thing: what about Errors? I wouldn't like to experience an unexpected shutdown if I were a user, I'd much rather that the application tells me that something went incredibly wrong and no one can do anything about it, "the end of the world is coming so I will exit right now". At least I would know that wasn't my fault lol.

Btw don't know if it's a good practice to catch errors... :\

There is a better way to do this in a Swing application?

like image 711
kelo Avatar asked Sep 09 '12 17:09

kelo


1 Answers

I think the best is to explicitly catch all checked exceptions, and install an uncaught exception handler for the rest. See this: How can I detect when an Exception's been thrown globally in Java?

This is how I use Thread.setDefaultUncaughtExceptionHandler:

public static void setupGlobalExceptionHandling() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            handleException(e);
        }
    });
}

Note that the "sun.awt.exception.handler" trick for the EDT thread, mentioned in many SO posts, is not necessary and does not work in Java 7. For Java 7 just use the standard Thread.setDefaultUncaughtExceptionHandler as described above. Of course, if you use both mechanisms to register the exception handler, the code will work in all versions.

BTW, the EDT thread is automatically restarted if an uncaught exception is thrown (but your app might remain in an inconsistent state), see this: EDT and runtime exception

like image 169
lbalazscs Avatar answered Sep 19 '22 18:09

lbalazscs