Default Exception Handling in Java - rahul00773/JavaConcepts GitHub Wiki

  1. Inside a method, if an exception occurs the method in which it is raised is responsible to create exception object by including the following information.

  2. Name of exception

  3. Description of exception

  4. Location at which exception occurs(stack trace)

  5. After creating an exception object method handover that objects to the JVM.

  6. JVM will check whether the method contains any exception handling code or not. If the method does not contain exception handling code then JVM terminates that method abnormally and removes the corresponding entry from the stack.

  7. Then JVM identified the caller method and checks whether the caller method contains any handling code or not. If the caller method does not contain handling code then JVM terminates that caller method also abnormally and removes the corresponding entry from the stack. This process will be continued until the main method. And if the main method also doesn't contain handling code then JVM terminates the main method also abnormally and removed the corresponding entry from the stack.

  8. Then JVM handovers responsibility of exception handling to the default exception handler. Which is part of the JVM.

  9. Default exception handler prints exception in the following format and terminates the program abnormally.

Exception in thread xxx(method name): Name of exception: Description stack trace

package src.exceptionHandling;

public class DefaultHandling {
    public static void main(String[] args){
        doStuff();
        }
        
        public static void doStuff(){
        
        doMoreStuff();
        }
        
        public static void doMoreStuff(){
        System.out.println(10/0);
    }}


Exception in thread "main" java.lang.ArithmeticException: / by zero
        at src.exceptionHandling.DefaultHandling.doMoreStuff(DefaultHandling.java:16)
        at src.exceptionHandling.DefaultHandling.doStuff(DefaultHandling.java:11)
        at src.exceptionHandling.DefaultHandling.main(DefaultHandling.java:6)



Example2:

```java
package src.exceptionHandling;

public class Example2 {

    public static void main(String[] args){
        doStuff();
        System.out.println(10/0);
        }
        
        public static void doStuff(){
        
        doMoreStuff();
        System.out.println("HI");
        }
        
        public static void doMoreStuff(){
        System.out.println("Hello");
    }
    
}```


Output:

Hello
HI
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at src.exceptionHandling.Example2.main(Example2.java:7)


Note: In a program, at least one method terminates abnormally then the program termination is abnormal termination. If all methods terminated normally then only program termination is normal termination.