Michael
Michael

Reputation: 3229

Java - listen when an exception is caught in an external class

Is there a way to create a listener in a separate class that runs a certain piece of code whenever an exception is caught within your project?

My code has a lot of try-catches in it, and if an exception is caught I would like to see the logs using log4j. I can do the following for every try-catch I have fairly easily (just with some time effort):

private static final Logger logger = LogManager.getLogger(Example.class);

public void testMethod() {
    try {
        // some code here that could throw an exception
    } catch(Exception e) {
        logger.error("Unexpected error has occurred: ", e);
    }
}

This will log the exception using log4j. However, I would need to do that over 50 times, and it's so redundant that I would rather be able to use 1 method to do that. So, is there a way to instead do something like this?

public class ListenerClass {

    private static final Logger logger = LogManager.getLogger(ListenerClass.class);

    // This method will be listening for exceptions to be caught within the project
    /**
     * @param e - The exception that was just caught
    */
    public void listenerMethod(ExceptionCaught e) {
        logger.error("An exception has been thrown: ", e);
    }

}

Is this possible?

Thanks

Upvotes: 1

Views: 1681

Answers (2)

payloc91
payloc91

Reputation: 3809

Standard way:

Thread.setDefaultUncaughtExceptionHandler( (thread, throwable) -> {
        log(throwable.getMessage(), thread.getId());
});

which will handle uncaught RuntimeExceptions, and unless otherwise specified it will act for all your application threads.

Just remember the Exceptions are thrown for a reason, and shouldn't be ignored, especially RuntimeExceptions.


If you are using an older version of java (before 8), you must explicitly instantiate an anonymous class:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
      @Override
      public void uncaughtException(final Thread t, final Throwable e) {

      }
}); 

Upvotes: 3

mancini0
mancini0

Reputation: 4703

Look at Thread.setDefaultUncaughtExceptionHandler()

Upvotes: 1

Related Questions