Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define custom exception handler in Java? [duplicate]

Tags:

java

exception

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.

like image 454
Benj Avatar asked Nov 28 '25 15:11

Benj


2 Answers

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

like image 60
Sleiman Jneidi Avatar answered Nov 30 '25 04:11

Sleiman Jneidi


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()));
like image 22
virgo47 Avatar answered Nov 30 '25 05:11

virgo47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!