In java projects, we handle exceptions using Centralized Exception Handling or Global Exception Handling mechanism. This is supported by most of the latest java technologies and frameworks.
In project, if any chance of checked exceptions we will catch them and wrap them into unchecked exceptions and rethrow them. So we could avoid exception handling code(try-catch blocks) all over the project. We define exception handling code only in one place called Global Exception handler.
Let’s see a an example of Global Exception Handler as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.vidvaan.corejava.exception27.global.exception.handler; public class GlobalExceptionHandler { public static void main(String[] args) { Handler globalExceptionHandler = new Handler(); Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler); new GlobalExceptionHandler().division(1, 0); } // this method raises unchecked exception ArithmeticException public int division(int num1, int num2) { return num1 / num2; } } // This global exception handler automatically invoked when main method not handled exception class Handler implements Thread.UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { System.out.println("Unhandled exception caught!" + e.getMessage()); } } |
Output :
Unhandled exception caught!/ by zero
In this example, We have a chance of unchecked exception(ArithemeticException) in division() method, but we didn’t handle exception either in division() method or main() method. But as you can see in the output the exception is not given to ‘default exception handler’ even it is not handled any where in the application. Because the exception is received by Global exception handler. In the Global Exception Handler, we could do what ever we want when that specific exception is raised. In this example just we are printing error message. In this way we could avoid exception handling code all over the application, But we are handling those exceptions with Global Exception Handler.
Spring like frameworks provides more sophisticated global exception handler support.