Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 783
Colin Avatar asked Aug 29 '11 14:08

Colin


1 Answers

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);
  }
}
like image 191
Nathan Hughes Avatar answered Sep 30 '22 04:09

Nathan Hughes