简体   繁体   中英

Handle all not handled exceptions

Is it possible to handle (a simple log writing) all not handled exceptions?

In more details, I need to log any exception that occurs anywhere in the code, log the exception and then continue (which might results into more exceptions obviously!).

You can use a Default Uncaught Exception Handler to catch any unhanded exceptions.

Is is also possible to set a specific handler per thread or thread group.

You could use AOP (Aspect Oriented Programming) for this. Specifically, you could create an aspect that logs all exceptions.

If you are using spring, you can use the AfterThrowing Advice Annotation for this.

here's 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM