How can I catch AWT thread exceptions in Java?

后端 未结 4 1055
时光取名叫无心
时光取名叫无心 2020-12-06 05:03

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

4条回答
  •  盖世英雄少女心
    2020-12-06 05:27

    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.

提交回复
热议问题