简体   繁体   中英

Catching Exceptions in Swing GUI application

I have a GUI Swing app.

Is there a way to catch all exceptions?

I have a made a Database Class that holds my database JDBC objects.

It is declared as a field in my Swing GUI Class.

e.g. 

public class MySwingGUI {

  protected Database database = new Database();

so if any exceptions propagate up from somewhere in the GUI code, I want to somehow handle it so that I can close the database connection.

any ideas?

Really your code should be catching exceptions where they occur, and handling them appropriately. The database only needs to be shut down under proper exit conditions.

Any unhandled exceptions on the UI thread will crash the application. In that case, you don't need to worry about closing the database; the app is dead.

What you might be looking for is the uncaught exception handler. Just set the uncaught exception handler on the UI thread.

See UncaughtExceptionHandler doc

This is more for debugging. Its not a good way to handle errors.

Another approach to handle exceptions in Swing . You can use something like this.

public class EventQueueProxy extends EventQueue {

    private static final Logger logger = Logger.getLogger( EventQueueProxy.class.getName() );

    protected void dispatchEvent( AWTEvent newEvent )
    {
        try {
            super.dispatchEvent( newEvent );
        } catch( RuntimeException | Error e ) {
            logger.error(e.getCause(),e);            
            JOptionPane.showMessageDialog( null, "someDescriptiveMessage");
        }
    }
}

And you can use a helper method to set it

    public static void captureUncaughtExceptionInEvent()
    {

            EventQueue queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
            queue.push(new EventQueueProxy());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM