Comment puis-je intercepter les exceptions de thread AWT en Java?
-
01-07-2019 - |
Question
Nous souhaitons que les traces de ces exceptions soient consignées dans les journaux de nos applications. Par défaut, Java les envoie à la console.
La solution
Il existe une distinction entre les exceptions non interceptées dans l'EDT et en dehors de l'EDT.
Une autre question a une solution pour les deux mais si vous voulez seulement la partie EDT mâchée ...
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())
}
}
Autres conseils
Depuis Java 7, vous devez le faire différemment car le hack sun.awt.exception.handler
ne fonctionne plus.
Voici la solution (extrait de Exceptions AWT non capturées dans 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());
}
});
Un petit ajout à la réponse de shemnon :
La première fois qu'une exception RuntimeException (ou une erreur) non capturée se produit dans l'EDT, elle recherche la propriété "sun.awt.exception.handler". et tente de charger la classe associée à la propriété. EDT a besoin que la classe Handler ait un constructeur par défaut, sinon EDT ne l'utilisera pas.
Si vous souhaitez apporter un peu plus de dynamisme à la manipulation, vous devez le faire avec des opérations statiques, car la classe est instanciée par l'EDT et n'a donc aucune chance d'accéder à d'autres ressources que statiques. Voici le code du gestionnaire d'exceptions de notre infrastructure Swing que nous utilisons. Il a été écrit pour Java 1.4 et a très bien fonctionné là-bas:
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);
}
}
J'espère que ça aide.
Il y a deux façons:
- / * Installer un Thread.UncaughtExceptionHandler sur l'EDT * /
- Définissez une propriété système: System.setProperty ("sun.awt.exception.handler", MyExceptionHandler.class.getName ());
Je ne sais pas si ce dernier fonctionne sur des jvms non SUN.
-
En effet, le premier n'est pas correct, il ne s'agit que d'un mécanisme permettant de détecter un thread bloqué.