Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch AWT thread exceptions in Java?

We'd like a trace in our application logs of these exceptions - by default Java just outputs them to the console.

like image 229
Nicolas Simonet Avatar asked Sep 18 '08 19:09

Nicolas Simonet


People also ask

Can you catch an exception thrown by another thread in Java?

There does not exist a way in Java to use try/catch around your start() method to catch the exceptions thrown from a secondary thread and remain multithreaded.

What is AWT exception in Java?

AWTException is a generic exception that can be thrown when an exceptional condition has occurred within AWT. None of the AWT classes throw this. If you subclass any of the AWT classes, you can throw an AWTException to indicate a problem.


1 Answers

Since Java 7, you have to do it differently as the sun.awt.exception.handler hack does not work anymore.

Here is the solution (from Uncaught AWT Exceptions in Java 7).

// Regular Exception
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());

// EDT Exception
SwingUtilities.invokeAndWait(new Runnable()
{
    public void run()
    {
        // We are in the event dispatching thread
        Thread.currentThread().setUncaughtExceptionHandler(new ExceptionHandler());
    }
});
like image 161
ToYonos Avatar answered Oct 11 '22 11:10

ToYonos