Pregunta

Nos gustaría tener un seguimiento de estas excepciones en los registros de nuestra aplicación; de forma predeterminada, Java simplemente las envía a la consola.

¿Fue útil?

Solución

Existe una distinción entre excepciones no detectadas en la EDT y fuera de la EDT.

Otra pregunta tiene solución para ambos. pero si solo quieres masticar la porción de 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())
  }
}

Otros consejos

Desde Java 7, debes hacerlo de manera diferente ya que sun.awt.exception.handler El truco ya no funciona.

Aquí está la solución (de Excepciones AWT no detectadas en 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());
    }
});

Una pequeña adición a shemnóns respuesta:
La primera vez que ocurre una RuntimeException (o error) no detectada en el EDT, busca la propiedad "sun.awt.exception.handler" e intenta cargar la clase asociada con la propiedad.EDT necesita que la clase Handler tenga un constructor predeterminado; de lo contrario, EDT no lo utilizará.
Si necesita aportar un poco más de dinámica a la historia de manejo, se verá obligado a hacerlo con operaciones estáticas, porque la clase es instanciada por el EDT y, por lo tanto, no tiene posibilidad de acceder a otros recursos que no sean estáticos.Aquí está el código del controlador de excepciones de nuestro marco Swing que estamos usando.Fue escrito para Java 1.4 y funcionó bastante bien allí:

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

}

Espero eso ayude.

Hay dos maneras:

  1. /* Instalar un Thread.UncaughtExceptionHandler en el EDT */
  2. Establecer una propiedad del sistema:System.setProperty("sun.awt.exception.handler",MyExceptionHandler.class.getName());

No sé si este último funciona en jvms que no son SUN.

--

De hecho, lo primero no es correcto, es sólo un mecanismo para detectar un hilo bloqueado.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top