Domanda

Vorremmo una traccia nei registri della nostra applicazione di queste eccezioni: per impostazione predefinita Java le invia semplicemente alla console.

È stato utile?

Soluzione

Esiste una distinzione tra eccezioni non rilevate nell'EDT e al di fuori dell'EDT.

Un'altra domanda ha una soluzione per entrambi ma se vuoi masticare solo la porzione di 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())
  }
}

Altri suggerimenti

A partire da Java 7, devi farlo diversamente come sun.awt.exception.handler l'hacking non funziona più.

Ecco la soluzione (da Eccezioni AWT non rilevate 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());
    }
});

Una piccola aggiunta a Shemnonrisposta:
La prima volta che si verifica una RuntimeException (o un errore) non rilevata nell'EDT, cerca la proprietà "sun.awt.exception.handler" e tenta di caricare la classe associata alla proprietà.EDT necessita che la classe Handler abbia un costruttore predefinito, altrimenti EDT non lo utilizzerà.
Se hai bisogno di portare un po' più di dinamica nella storia della gestione sei costretto a farlo con operazioni statiche, perché la classe viene istanziata dall'EDT e quindi non ha alcuna possibilità di accedere ad altre risorse oltre a quelle statiche.Ecco il codice del gestore delle eccezioni del nostro framework Swing che stiamo utilizzando.È stato scritto per Java 1.4 e lì ha funzionato abbastanza bene:

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

}

Spero che sia d'aiuto.

Ci sono due modi:

  1. /* Installa un Thread.UncaughtExceptionHandler sull'EDT */
  2. Imposta una proprietà di sistema:System.setProperty("sun.awt.exception.handler",MyExceptionHandler.class.getName());

Non so se quest'ultimo funzioni su jvms non SUN.

--

In effetti, il primo non è corretto, è solo un meccanismo per rilevare un thread in crash.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top