2008-09-18 10 views

Respuesta

10

Existe una distinción entre las excepciones no detectadas en el EDT y fuera del EDT.

Another question has a solution for both pero si quieres sólo la parte EDT masticado ...

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()) 
    } 
} 
+2

No hay necesidad de atrapar arrojable. No habrá bucle infinito. java.awt.EventDispatchThread.handleException detecta cualquier excepción para usted. –

+0

Dijo 'clases AWTExceptionHandler' –

0

Hay dos maneras:

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

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

-

De hecho, la primera no es correcto, es sólo un mecanismo para detectar un hilo estrellado.

+1

El uso de Thread.UncaufhtExceptionHandler no detectará las excepciones EDT. La clase EDT capta todos los objetos susceptibles de ser arrojados y los imprime en lugar de dejarlos desenrollar todo el hilo. – shemnon

+0

También le faltan detalles sobre lo que se necesita en la segunda opción, la clase MyExceptionHandler debe tener un método de instancia de manejador (Throwable) accesible y un constructor sin argumentos accesible. – shemnon

3

Una pequeña adición a shemnon s anwer:
La primera vez que un RuntimeException no detectada (o error) se produce en el EDT está buscando la propiedad "sun.awt.exception.handler" e intenta cargar la clase asociada a la propiedad. EDT necesita que la clase Handler tenga un constructor predeterminado, de lo contrario, el EDT no lo usará.
Si necesita incorporar un poco más de dinámica en la historia de manejo, está obligado a hacerlo con operaciones estáticas, porque la clase está 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 excepción 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 que ayude.

10

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

Here is the solution (de 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()); 
    } 
}); 
Cuestiones relacionadas