Exception Handling - Default Exception Handling

Exception Handling - Default Exception Handling
Before going to the definition, we will see a small example of  a routine of a school student.
Lets say if the school starts at 9 am.

1. Student has to wake up in the morning at 6:30 AM
2. Student has to take breakfast at 7:30 AM
3. Student has to take the school bus at 8 AM
4. Student will reach the school at 8:30 AM, attends the school prayer and will go to the class and start listening to lectures.

Now in a weekday unexpectedly student suffered from fever and the doctor advises the student to take rest, now the entire routine like waking up in the morning, having breakfast, going to school and listening lectures got disturbed. What is here the unexpected event? Student felling sick, this is an exception.

What is an Exception ? 

An unwanted or unexpected event which disturbs the entire flow of the application.


Why to handle Exceptions?

It is highly recommended to handle the exceptions, the main objective of exceptional handling is "graceful termination of the program" or handle the program in such a way that rest of the program will be executed.


Default Exception Handling in Java

Before going to Default Exception Handling we not to know, what is Runtime Stack Mechanism, 

What is Runtime Stack?

JVM creates a stack in the stack area, in which the list of methods to be executed by a thread at the runtime.

For each Thread, a new runtime stack is created.

what is Runtime Stack Mechanism? 

When a thread is executed, run time stack is created.
After successful execution, JVM checks each stack frame in the stack, whether the method is executed is successfully, its checks by one by one and removes the entry the from the stack. once all the entries are removed, the empty is stack is destroyed by JVM.

This complete process is called Runtime Stack Mechanism
Lets represent it programmatically
package com.learning.exceptionhandling;

public class SampleClass {

 public static void main(String... args) {
  callfirstMethod();
 }

 public static void callfirstMethod() {
  callSecondMethod();
 }

 public static void callSecondMethod() {
  printTheName();
 }

 public static void printTheName() {
  System.out.println("Bharani Ravi Kanth R");
 }

}

When we run this code, here the code starts from main method so, thread name by default given to as main thread.

first an JVM creates an empty stack, then it provides the list of "stack frames" which are to be executed by the Thread.


 -----------------------------
|                             |
 -----------------------------
  Runtime Stack


main thread will start executing from main method, thread makes an entry of main method in the stack.


 -----------------------------
|        main()               |
 -----------------------------
    Runtime Stack

Now the list of methods calls which are to be done will be entered.

 -----------------------------
|  printTheName()            |
 -----------------------------
|  callsecondMethod()        |
 -----------------------------
|  callfirstMethod()         |
 -----------------------------
|  main()                    |
 -----------------------------
  Runtime Stack


Now, after the execution of all the methods are successful by the thread, JVM will remove the stack frames one by one from the Stack. Since its a stack, Last in record will be removed first, PrintTheName() will be removed first and main() method is removed. After the Removal of all the stack frames, JVM will destroy the stack.

Now we will see what Default Exception Handling. lets create a class SampleClass.java

package com.learning.exceptionhandling;

public class SampleClass {

 public static void main(String... args) {
  callfirstMethod();
 }

 public static void callfirstMethod() {
  callSecondMethod();
 }

 public static void callSecondMethod() {
  calculate();
 }

 public static void calculate() {
  System.out.println(1/0);
 }
}

We already know 1/0 application will throw an exception, but the below code we didn't handle the exception, so it will be JVM's hand to handle the exception.

 When we run the code,
1. JVM first creates the empty runtime stack in the stack area,
2. JVM will enter the stack frames (information regarding the method call) into the stack as below


 -----------------------------
|  calculate()               |
 -----------------------------
|  callsecondMethod()        |
 -----------------------------
|  callfirstMethod()         |
 -----------------------------
|  main()                    |
 -----------------------------
  Runtime Stack

when the thread "main" starts executing the code, starts from main()->callfirstMethod()->callSecondMethod()->calculate(),

now the calculate method will throw the exception because we trying to print the value 1/0,

Now lets see how JVM handles the situation,

1. when the exception is triggered, JVM goes to the calculate method, checks for the calculate method has handled the exception or not. Calculate method has no handling of exception.

2.  Now JVM goes to the method which called calculate() method, i.e, callsecondMethod() method, and checks here whether this method has handled the exception, callsecondMethod() method didn't handle the execption,

3. Now JVM goes to the method which called callsecondMethod() method, i.e, callfirstMethod() method and checks here whether this method has handled the exception or not,callfirstMethod() method handle the exception.

4. Now JVM goes to the main method has handled the exception since it called callfirstMethod() method,

5. Since none of the methods handled the exception now its JVM turns to handle it, So JVM calls its "Default Exception Handler" to handle the current situation of the code, this exception handler will forcefully stop the application, and print the trace of the runtime stack or also called as StackTrace which is recorded by the JVM from the starting point of the exception to the method where the actual flow started, once the stack trace is printed JVM destroys the stack.

Default Exception Handler will print stacktrace  as below for format:

Exception in thread "name of the thread" ExceptionClass(with package) : Exception caused by description
          at  ClassName(with package).method (StartingPointOftheExceptionClassName.java:lineNumber of the exception)
          at  ClassName(with package).method (ClassName.java:line number of the code inside the method caused the exception)
          at  ClassName(with package).method (ClassName.java:line number of the code inside the method caused the exception)
          .
          .
          .
          .
          .
         FlowStartedClass(with package).method(FlowStartedClass.java:line number of the code inside the method caused the exception)

Lets the above example SampleClass.java

package com.learning.exceptionhandling;

public class SampleClass {

 public static void main(String... args) {
  callfirstMethod();
 }

 public static void callfirstMethod() {
  callSecondMethod();
 }

 public static void callSecondMethod() {
  calculate();
 }

 public static void calculate() {
  System.out.println(1/0);
 }
}

If we execute the code, Default Exception Handler will handle the situation and prints the below stacktrace.

Exception in thread "main" java.lang.ArithmeticException: / by zero
 at com.learning.exceptionhandling.SampleClass.calculate(SampleClass.java:18)
 at com.learning.exceptionhandling.SampleClass.callSecondMethod(SampleClass.java:14)
 at com.learning.exceptionhandling.SampleClass.callfirstMethod(SampleClass.java:10)
 at com.learning.exceptionhandling.SampleClass.main(SampleClass.java:6)


1. "main" is the thread name
2. "java.lang.ArithmeticException" Type of Exception, its class name with package,
3. "/ by zero" reason for the exception.
4. "com.learning.exceptionhandling.SampleClass.calculate" is the where the execption occured.
5. "(SampleClass.java:18)" is at the line number thrown the exception.
6. "com.learning.exceptionhandling.SampleClass.main" is where the flow has started"