如何在Java中捕获AWT线程exception?

我们想在我们的应用程序日志中跟踪这些exception – 默认情况下,Java只是将它们输出到控制台。

EDT中和EDT之外的未捕获exception之间存在区别。

另一个问题是两者都有解决方案,但如果你只想让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()) } } 

从Java 7开始,你必须以不同的方式执行它,因为sun.awt.exception.handler hack不再起作用了。

这是解决方案 (来自Java 7中的Uncaught AWT Exceptions )。

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

shemnon s anwer的一点点补充:
第一次在EDT中发生未捕获的RuntimeException(或Error)时,它正在查找属性“sun.awt.exception.handler”并尝试加载与该属性关联的类。 EDT需要Handler类具有默认构造函数,否则EDT将不使用它。
如果你需要为处理故事带来更多动态,你必须使用静态操作来执行此操作,因为该类由EDT实例化,因此没有机会访问除静态之外的其他资源。 这是我们正在使用的Swing框架中的exception处理程序代码。 它是为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); } } 

希望能帮助到你。

有两种方法:

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

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

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