如何在 Java 中捕获 AWT 线程异常?

发布于 2024-07-05 09:33:49 字数 50 浏览 9 评论 0 原文

我们希望在应用程序日志中跟踪这些异常 - 默认情况下 Java 仅将它们输出到控制台。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

何处潇湘 2024-07-12 09:33:49

从 Java 7 开始,您必须采取不同的方式,因为 sun.awt.exception.handler hack 不再起作用。

这是解决方案(来自Java 7 中未捕获的 AWT 异常)。

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

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());
    }
});
酒与心事 2024-07-12 09:33:49

EDT 内和 EDT 外的未捕获异常之间存在区别。

另一个问题有一个解决方案两者都,但如果你只想咀嚼 EDT 部分......

class AWTExceptionHandler {

  public void handle(Throwable t) {
    try {
      // insert your exception handling code here
      // or do nothing to make it go away
    } catch (Throwable t) {
      // don't let the exception get thrown out, will cause infinite looping!
    }
  }

  public static void registerExceptionHandler() {
    System.setProperty('sun.awt.exception.handler', AWTExceptionHandler.class.getName())
  }
}

There is a distinction between uncaught exceptions in the EDT and outside the EDT.

Another question has a solution for both but if you want just the EDT portion chewed up...

class AWTExceptionHandler {

  public void handle(Throwable t) {
    try {
      // insert your exception handling code here
      // or do nothing to make it go away
    } catch (Throwable t) {
      // don't let the exception get thrown out, will cause infinite looping!
    }
  }

  public static void registerExceptionHandler() {
    System.setProperty('sun.awt.exception.handler', AWTExceptionHandler.class.getName())
  }
}
假扮的天使 2024-07-12 09:33:49

shemnon的回答进行一点补充:
第一次在 EDT 中发生未捕获的 RuntimeException(或错误)时,它会查找属性“sun.awt.exception.handler”并尝试加载与该属性关联的类。 EDT 需要 Handler 类有一个默认构造函数,否则 EDT 将不会使用它。
如果您需要在处理故事中引入更多动态,则必须使用静态操作来执行此操作,因为该类是由 EDT 实例化的,因此没有机会访问除静态之外的其他资源。 这是我们正在使用的 Swing 框架中的异常处理程序代码。 它是为 Java 1.4 编写的,并且运行得很好:

public class AwtExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(AwtExceptionHandler.class);

    private static List exceptionHandlerList = new LinkedList();

    /**
     * WARNING: Don't change the signature of this method!
     */
    public void handle(Throwable throwable) {
        if (exceptionHandlerList.isEmpty()) {
            LOGGER.error("Uncatched Throwable detected", throwable);
        } else {
            delegate(new ExceptionEvent(throwable));
        }
    }

    private void delegate(ExceptionEvent event) {
        for (Iterator handlerIterator = exceptionHandlerList.iterator(); handlerIterator.hasNext();) {
            IExceptionHandler handler = (IExceptionHandler) handlerIterator.next();

            try {
                handler.handleException(event);
                if (event.isConsumed()) {
                    break;
                }
            } catch (Throwable e) {
                LOGGER.error("Error while running exception handler: " + handler, e);
            }
        }
    }

    public static void addErrorHandler(IExceptionHandler exceptionHandler) {
        exceptionHandlerList.add(exceptionHandler);
    }

    public static void removeErrorHandler(IExceptionHandler exceptionHandler) {
        exceptionHandlerList.remove(exceptionHandler);
    }

}

希望它有所帮助。

A little addition to shemnons anwer:
The first time an uncaught RuntimeException (or Error) occurs in the EDT it is looking for the property "sun.awt.exception.handler" and tries to load the class associated with the property. EDT needs the Handler class to have a default constructor, otherwise the EDT will not use it.
If you need to bring a bit more dynamics into the handling story you are forced to do this with static operations, because the class is instantiated by the EDT and therefore has no chance to access other resources other than static. Here is the exception handler code from our Swing framework we are using. It was written for Java 1.4 and it worked quite fine there:

public class AwtExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(AwtExceptionHandler.class);

    private static List exceptionHandlerList = new LinkedList();

    /**
     * WARNING: Don't change the signature of this method!
     */
    public void handle(Throwable throwable) {
        if (exceptionHandlerList.isEmpty()) {
            LOGGER.error("Uncatched Throwable detected", throwable);
        } else {
            delegate(new ExceptionEvent(throwable));
        }
    }

    private void delegate(ExceptionEvent event) {
        for (Iterator handlerIterator = exceptionHandlerList.iterator(); handlerIterator.hasNext();) {
            IExceptionHandler handler = (IExceptionHandler) handlerIterator.next();

            try {
                handler.handleException(event);
                if (event.isConsumed()) {
                    break;
                }
            } catch (Throwable e) {
                LOGGER.error("Error while running exception handler: " + handler, e);
            }
        }
    }

    public static void addErrorHandler(IExceptionHandler exceptionHandler) {
        exceptionHandlerList.add(exceptionHandler);
    }

    public static void removeErrorHandler(IExceptionHandler exceptionHandler) {
        exceptionHandlerList.remove(exceptionHandler);
    }

}

Hope it helps.

泪是无色的血 2024-07-12 09:33:49

有两种方法:

  1. /* 在 EDT 上安装 Thread.UncaughtExceptionHandler */
  2. 设置系统属性:
    System.setProperty("sun.awt.Exception.handler",MyExceptionHandler.class.getName());

我不知道后者是否适用于非 SUN jvm。

--

事实上,第一个是不正确的,它只是一种检测崩溃线程的机制。

There are two ways:

  1. /* Install a Thread.UncaughtExceptionHandler on the EDT */
  2. Set a system property:
    System.setProperty("sun.awt.exception.handler",MyExceptionHandler.class.getName());

I don't know if the latter works on non-SUN jvms.

--

Indeed, the first is not correct, it's only a mechanism for detecting a crashed thread.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文