How do I catch this exception in Swing?

后端 未结 5 1938
滥情空心
滥情空心 2021-01-02 09:09

I have a Swing application, and even though I have everything in a try/block, the exception isn\'t caught.

public static void main(         


        
5条回答
  •  攒了一身酷
    2021-01-02 09:50

    As mentioned by another poster, your problem is that the exception is being thrown in another thread, the event dispatch thread. A couple of solutions:

    • put a try/catch around the actual code where the exception is occurring: e.g. if it's in response to a button click handled by an ActionListener, put the try/catch inside your actionPerformed() method;
    • or, leave the exception as an uncaught exception, and add an uncaught exception handler. For example:
    
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
          public void uncaughtException(Thread t, Throwable e) {
            // ... do something with exception here ...
          }
        });
    

    On a side-note, you should in principle but your UI startup code in a SwingUtilities.invokeLater().

提交回复
热议问题