Java Exception Handler

In this tutorial we will look at an alternative approach to handling exceptions that allows a client to pass a lambda or some component to customize the exception handling. This technique is useful as it allows the client of your code to decide how they would like to handle the exception. Instead of your code handling, throwing or logging an exception the client passes some code via an exception handler to customize the exception handling logic.

1
2
3
4
@FunctionalInterface
public static interface ExceptionHandler {
    public void handle(Exception e, String errorMessage);
}

Above we define a Functional Interface called ExceptionHandler this interface has one method that accepts an exception and an error message.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public static void readResource(String file, ExceptionHandler handler) {
    try (FileInputStream is = new FileInputStream(ResourceUtils.getFileFromResources(file))) {
        int data = is.read();
        while (data != -1) {
            System.out.print((char) data);
            data = is.read();
        }
    }
    catch(Exception e) {
        handler.handle(e, "Unable to read file");
    }
}

In the above code we create a simple utility method for demonstration purposes that reads a resource file. The client passes in the name of the resource and the exception handler to handle any exception. The catch clause in the readResource method does not wrap, rethrow or log any raised exceptions. Any rasied Java exceptions are passed to the ExceptionHandler instance’s handle() method. The Exception Handler can decide for itself how it wants to process the Exception.

1
2
3
public static void main(String[] args) {
    readResource("does-not-exist.txt", (e,errorMessage) -> System.out.println("Unable to read file"));
}

Above we call the readResource method that passes an exception handler as a lambda expression. When the above code is executed it outputs:

1
Unable to read file

When To Use The Exception Handler

The approach of using an Exception Handler is useful in situations where the exception thrown can be handled in different ways. Moreover, it is useful when some code is performing a task such as processing files, parsing XML and we may or may not want to terminate the task depending on what exception occurs. By allowing the client of our task to pass the exception handling code the client can make the decision of how to handle the exception following a more event based approach.

There is no standard Exception Handler implementation and you can follow the pattern in your own applications by creating an ExceptionHandler customized to the needs of your application.