Define custom exception handler in Java? [duplicate]

这一生的挚爱 提交于 2019-12-10 11:35:42

问题


Well ! Thanks for having found the answer. I accepted the duplicate since it is exactly what I wanted and it is well explained. Thanks to everybody for your answers :)

Does anyone have advice or some idea on how to make a custom exception handler in Java ?

I mean modifying the standard Java exception handling method for code-uncatched Exceptions, Errors and more generically Throwable.

The PHP way to do this is to define a custom exception handler, but it seems there is no such way in Java.

The goal I would achieve is to insert a custom process in the Java error handling process :

Uncatched Throwable -> handling "outside my code" by the JVM -> my custom process -> resume JVM standard exception handling if wanted

Thanks to all for any idea or suggestion !

Edit after your answers

Is there a way to generify this handler to all threads without declaring explicitly in each thread ? I opened a new question here for this topic.


回答1:


Just mind you, Java is multithreaded, and exception are related to their threads. If the Exception was uncaught you can use thread.setUncaughtExceptionHandler.

 thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println("catching exception "+e.getMessage());
        }
    });

Or you can use the AOP approach and define an advice to handle exceptions. Have a look at AspectJ.

Note: You need to be careful here because you might end up swallowing exceptions and having hard time figuring out the source of bugs




回答2:


Yes you can use Thread.setDefaultUncaughtExceptionHandler(CustomHandler)

The JVM allows you to customize that through the implementation of the Thread.UncaughtExceptionHandler interface

So basically

public class MyHandler implements Thread.UncaughtExceptionHandler {
  @Override
  public void uncaughtException(Thread t, Throwable e) {
     // handle the exception
   }
}



回答3:


This can be done per thread like this:

public static void main(String[] args) {
    Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override public void uncaughtException(Thread t, Throwable e) {
            System.out.println("Caught: " + e.toString());
        }
    });
    throw new RuntimeException();
}

With setting the UncaughtExceptionHandler it prints Caught: java.lang.RuntimeException instead of classic stack trace.

And Java 8 version with lambda:

Thread.currentThread().setUncaughtExceptionHandler(
        (t, e) -> System.out.println("Caught: " + e.toString()));


来源:https://stackoverflow.com/questions/33343457/define-custom-exception-handler-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!