What If we don’t handle Exception
If we don’t handle the Exception in our code, JVM’s ‘Default Exception Handler’ handles the Exception. But ‘Default Exception Handler’ just prints the exception on the console and terminates the application. But ‘Default Exception Handler’ really don’t know how to handle the exception as per our application requirement. So we should always handle the exception in our code as per our business needs.
How ‘Default Exception Handler’ works in Java
If our code violates JVM rules in the execution of the code, then JVM creates an exception object with the following information.
- Name of the Exception
- Description of the Exception
- Call Stack(Location of the Exception)
- JVM checks whether the method(in which exception raised) contains any exception handling code or not. If the method doesn’t contain any handling code then JVM terminates that method abnormally and removes corresponding entry from the stack.
- JVM identifies the caller method and checks whether the caller method contains any exception handling code or not. If the caller method also doesn’t contains exception handling code then JVM terminates that caller method abnormally and removes corresponding entry from the stack.
- This process will be continued until main() method and if the main() method also doesn’t contains any exception handling code then JVM terminates main() method and removes corresponding entry from the stack.
- Then JVM handovers the responsibility of exception handling to the ‘Default Exception Handler’
- ‘Default Exception Handler’ just print exception information to the console in the following format and terminates the program abnormally.
Name of the Exception: Description
Stack trace(Location of the Exception)
Example : DefaultExceptionHandlerExample.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.vidvaan.corejava.exception02.defaultExceptionHandler; // Default Exception Handler public class DefaultExceptionHandlerExample { // If even main method don't handled exception, It will be handover to 'Default // Exception Handler' public static void main(String[] args) { method1(); } static void method1() { method2(); } static void method2() { method3(); } static void method3() { System.out.println(5 / 0); } } |
Output
Exception in thread “main” java.lang.ArithmeticException: / by zero
at com.vidvaan.corejava.exception02.defaultExceptionHandler.DefaultExceptionHandlerExample.method3(DefaultExceptionHandlerExample.java:21)
at com.vidvaan.corejava.exception02.defaultExceptionHandler.DefaultExceptionHandlerExample.method2(DefaultExceptionHandlerExample.java:17)
at com.vidvaan.corejava.exception02.defaultExceptionHandler.DefaultExceptionHandlerExample.method1(DefaultExceptionHandlerExample.java:13)
at com.vidvaan.corejava.exception02.defaultExceptionHandler.DefaultExceptionHandlerExample.main(DefaultExceptionHandlerExample.java:9)