Capture exception in swing thread
How to send exception to log4j log from java swing ?
We have much code already done and it does a lot of:
mytable.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
... no try catch
}
});
There is no try/catch. App sends npe exception to console. We need it in log4j. But don't want to change all this 开发者_开发知识库code (100s of line like this). What can we do?
You can set up an uncaught-exception handler that will log anything thrown by your application.
In the main method of your Swing app add these lines:
Thread.setDefaultUncaughtExceptionHandler(new LoggingExceptionHandler());
System.setProperty("sun.awt.exception.handler", LoggingExceptionHandler.class.getName());
Then implement the exception-handler like this:
package com.initech.tps;
import java.lang.Thread.UncaughtExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggingExceptionHandler implements UncaughtExceptionHandler
{
private static final Logger logger = LoggerFactory.getLogger(LoggingExceptionHandler.class);
@Override
public void uncaughtException(Thread t, Throwable e)
{
logger.error("caught exception in thread: " + t.getName(), e);
}
}
You also can wrap the EventQueue like in this example: Catch exceptions in javax.swing application
If you want also log the exception, here I give you other option, maybe with more code, but it works properly.
import java.awt.AWTEvent;
import java.awt.EventQueue;
import javax.swing.JOptionPane;
import org.slf4j.Logger;
public class QueueEvenement extends EventQueue {
// CONSTRUCTOR
public QueueEvenement(Logger logger) {
super();
this.logger = logger;
}
protected void dispatchEvent(AWTEvent newEvent) {
try {
super.dispatchEvent(newEvent);
} catch (Throwable t) {
// Write log
logger.error(String.format("Erreur inconnue (%s - %s)",
t.getClass().getName(), t.getLocalizedMessage()));
}
}
}
After you code this class, you can install the wrap with the following line:
Toolkit.getDefaultToolkit().getSystemEventQueue().push(new EventQueueProxy());
This solution have the advantage of catch only the graphic, giving you more flexibility when you have to differentite between graphic exceptions (including the event handlers) and the other possible exceptions.
Regards!
精彩评论