Handle all unhandled exceptions

Is it possible to handle (a simple log entry) all unhandled exceptions?

In more detail, I need to register any exception that occurs anywhere in the code, register an exception and then continue (which can lead to more significant exceptions!).

+3
source share
3 answers

You can use the Default Uncaught Exception Handler to catch any inexhaustible exceptions.

You can also set a specific handler for a stream or group of threads.

+5
source

AOP (Aspect Oriented Programming). , , .

spring, AfterTrowing Advice Annotation .

+1

here is a piece of code that could help you:

public class MyDefaultExceptionHandler extends DefaultExceptionHandler
  {

  private UncaughtExceptionHandler defaultUEH;

  public MyDefaultExceptionHandler() 
    {
    this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    }

  @Override
  public void uncaughtException(Thread t, Throwable e) 
    {
    //print anything you wish about the Throwable e :getStackTrace(), getCause(), getClass()...
    defaultUEH.uncaughtException(t, e); //this will call the default handling of the exception (crash...)
    }
  }
//in the main app:
Thread.setDefaultUncaughtExceptionHandler(new MyDefaultExceptionHandler());
0
source

All Articles