2

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.

Community
  • 1
  • 1
Benj
  • 1,184
  • 7
  • 26
  • 57

3 Answers3

5

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

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
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()));
virgo47
  • 2,283
  • 24
  • 30
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
   }
}
Sam
  • 2,950
  • 1
  • 18
  • 26