Handle exceptions in java projects

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.

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.

Scroll to Top