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

时间:2020-03-06 14:22:58  来源:igfitidea点击:

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

解决方案

有两种方法:

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

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

--

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

在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())
  }
}

对shemnons的一些补充:
EDT中第一次发生未捕获的RuntimeException(或者Error)时,它正在寻找属性" 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);
    }

}

希望能帮助到你。