Java- Exception Handling

Exception Handling

The unexpected unwanted event which disturbs entire flow of the program is known as -Exception”

  • If we are not handling exception, the program may terminate abnormally without releasing allocated resources.

  • Exception handling means it is not repairing an exception, just providing alternative way to continue the program execution normally.


Common scenarios where exceptions may occur

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException

If we have null value in any variable, performing any operation occurs a NullPointerException.

String s=null;  
System.out.println(s.length());//NullPointerException

The wrong formatting of any value, may occur NumberFormatException.

String s="abc";  
int i=Integer.parseInt(s);//NumberFormatException

If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException

int a[]=new int[5];  
a[10]=50; //ArrayIndexOutOfBoundsException


Default Exception Handling

  • Whenever an exception raised, the method in which it is raised is responsible for the preparation of exception object by including the following information

    Name of Exception.
    Description.
    Location of Exception
    
  • After preparation of Exception Object, the method handovers the object to the JVM, JVM will check for Exception handling code in that method.

  • If the method doesn’t contain any exception handling code, then JVM terminates that method abnormally and removes corresponding entry from the stack.

  • JVM will check for exception handling code in the caller and if the caller method also doesn’t contain 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, if the main method also doesn’t contain any exception handling code then JVM terminates main method abnormally.

  • Just before terminating the program JVM handovers the responsibilities of exception handling to default exception handler.

  • Default exception handler prints the error in the following format.

    Name of Exception: Description
    stackTrace