Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

java - Debug exceptions in AWT queue thread

I am developing a Swing application with a component performing custom painting. When I make some mistake in the painting code and an exception is thrown, the situation is hard to debug. Instead of being caught by the debugger, a popup shows with the exception information. Moreover, the thread seems to be restarted, and as the exception is a result of coding error, it is shown again and again.

When I am lucky enough to switch into the debugger (which is difficult, because more and more popups keep coming as the application gets paint requests), the debugging console shows me an exception information like:

SEVERE: Uncaught exception thrown in Thread[AWT-EventQueue-0,6,main]

.... stack follows

My application is written in Scala and I am using IntelliJ IDEA 14. My uncaught main thread exceptions are handled fine by the debugger (I have Uncaught exception enabled for Any exception breakpoint enabled in the Java Exception Breakpoints), but exceptions in AWT threads are not.

I have tried installing a handler as described in this How can I detect when an Exception's been thrown globally in Java? answer, but my handler does not seem to be triggered.

I would like to achieve following (in order of importance):

  1. avoid the AWT thread restarting on exception, or at least prevent the popup from showing
  2. handle uncaught exceptions in the debugger instead of being printed in the console

(Note: while this is Scala application, I assume the behaviour would be the same for Java, hence the Java tag).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to this link, you have to handle both regular Exception and EDT Exception without using the old sun.awt.exception.handler hack (which does not work anymore since Java 7)

Here is your ExceptionHandler

public static class ExceptionHandler implements Thread.UncaughtExceptionHandler
{
    public void uncaughtException(Thread thread, Throwable thrown)
    {
        // TODO handle your Exception here
    }
}

Usage :

// 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());
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...