Recent Posts

Tuesday, 12 July 2016

Exception Handling Tutorial


     An unwanted unexpected event that disturbs normal flow of the program is called Exception.
* It is highly recommended to handle exceptions.

* Exception handling doesn't mean repairing an exception. It means providing alternative way to continue rest of the program normally.

      For example if our programming requirement is to read data from a file which is available at remote machine and at run time if that remote machine file is not available then our program should not be terminated abnormally.
     As  alternative provide a local file to continue rest of the program normally. This way of providing alternative way is nothing but Exception Handling.

* The main objective of Exception Handling is graceful termination of the program (Normal termination of the program)

Runtime Stack Mechanism
* For every thread JVM will create a runtime stack.

* All the method calls performed by the thread will be sorted in the corresponding runtime stack.

* Each entry in the Runtime stack is called stack frame or activation record.

* Once if the method execution completes corresponding entry will be removed from the Runtime Stack.

* Once if all the methods execution completed then empty runtime stack will be destroyed by JVM just before terminating the thread.

* This entire process is called Runtime Stack mechanism.
E.g
class ExceptionDemo {
   public static void main(String[] args) {
      doStuff();
   }
   public static void doStuff() {
      doMoreStuff();
   }
   public static void doMoreStuff() {
      System.out.println("Hi this is Exception ...........Thread");
   }
}


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


      In our program while executing any method if an exception raised then the corresponding method is responsible to create exception object by including the following information.
1. Name of Exception.
2. Description.
3. 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 and 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

Exception Hierarchy
Throwable is the parent of entire java exception hierarchy. It has 2 child classes
1. Exception
     These are recoverable. Most of the cases exceptions are raised due to program code only.

2. Error
     Errors are non-recoverable. Most of the cases errors are due to lack of system resources but not due to our programs.

Checked Vs UnChecked
     The Exceptions which are checked by the compiler for smooth execution of the program at runtime are called ‘checked exception’
E.g
IOException, ServletException, InterruptedException.

   The Exceptions which are unable to checked by the compiler are called ‘unchecked exceptions’. Runtimeexception and it’s child classes, Error and it’s child classes are considered as unchecked exceptions and all the remaining considered as checked.

    Whether the exception is checked or unchecked it always occur at runtime only.

Partially checked Vs fully checked
     A checked exception is said to be fully checked iff all it’s child classes also checked.
E.g
IOException.

    A checked exception is said to be partially checked if some of it’s child classes are not checked.
E.g
Exception, Throwable.

Exception Handling By Using try ,catch
     We have to place the risky code inside the try block and the corresponding exception handling code inside catch block.

try {
   //Risky code
}
catch (X e) {
//handling code
}
Without Exception handling code

Control Flow in try, catch
try {
   statement 1;
   statement 2;
   statement 3;
} 
catch (X e) {
   statement 4;
}
statement 5;
Case 1: If there is no exception
1,2,3,5 normal

Case 2: If there is an exception raised at statement 2 and the corresponding catch block matched.
1,4,5 normal termination.

Case 3: if an exception raised at statement 2 but the corresponding catch block is not matched
1 Abnormal termination.

Case 4: if an exception raised at statement 4 or statement 5 it is always abnormal termination.

The Methods to display Exception Information
     Throwable class contains the following methods to display error information.
printStackTrace
     It displays error information in the following format.
Name of Exception : Description
StackTace.

toString
     It displays error in the following format.
Name of Exception : Description

getMessage
     It displays error information in the following format.
Description

Note
     Default Exception handler always uses printStackTrace method only.

try with multiple catch blocks
     The way of handling exception is valid from exception to exception. Hence for every exception we should define corresponding catch blocks hence try with multiple catch blocks is possible.
try {
   risky code
}
catch (ArithmeticException e ) {
   //handler to A.E
}
catch (NullPointerException e) {
   //handler for N.P.E
}
catch(IOException e) {
   //handler for IOException
}
catch(Exception e) {
   //handler for Exception
}
     In the case of try with multiple catch blocks the order of catch blocks is important. And it should be from child to parent other wise Compiler Error. Saying Exception xxx has already been caught
try {
   risky code
}
catch (ArithmeticException e ) {  //Fine
}
catch (Exception e){
}

try {
   risky code
}
catch (Exception e ) {  
}
catch (ArithmeticException e){ //Error
}
C.E java.lang.ArithmeticException has already been caught
     If there is no chance of raising an exception in try statement then we are not allowed to maintain catch block for that exception violation leads to compile time error but this rule is applicable only for fully checked exceptions.
try {
   System.out.println("Hi");
}
catch (ArithmeticException e) {
}

try {
   System.out.println("Hi");
}
catch (Exception e){
}

try {
   System.out.println("Hi");
}
catch (IOException e) {
}
C.E: java.io.IOException is never thrown in body of corresponding try statement

try {
   System.out.println("Hi");
}
catch (InterruptedException e) {
}
C.E: InterruptedException is never thrown in body of corresponding try statement

finally
    It is not recommended to place cleanup code inside try statement because there is no guarantee for execution of all statements inside try block.

     It is not recommended to maintain cleanup code with in the catch block because if there is no execution the catch blocks won’t be executed.

     We required a block to maintain cleanup code which should execute always irrespective of whether the exception is raised or not whether it is handled or not , such block is nothing but “finally block”
     Hence the main objective of finally block is to maintain cleanup code.
try {
   //open the database connection
   //read the data
}
catch (X e) {
}
finally {
   close the Connection
}
E.g
try {
   System.out.println("try");
}
catch (ArithmeticException e) {
   System.out.println("catch");
}
finally {
   System.out.println("finally");
}
Output

try
finally
Normal
Termination

try {
   System.out.println(10/0);
}
catch (ArithmeticException e) {
   System.out.println("catch");
}
finally {
   System.out.println("finally");
}
Output
 
catch
finally
Normal
Termination
try {
   System.out.println(10/0);
}
catch (NullPointerException e) {
   System.out.println("catch");
}
finally {
   System.out.println("finally");
}
Output
finally
Abnormal termination 
     Hence finally block should always execute irrespective of whether the execution is raised or not raised or handled or not handled.

     The finally block won’t be executed if the system it self exists(JVM shutdown) i.e in the case of System.exit() finally block won’t be executed.
E.g
try {
   System.out.println("Hi");
   System.exit(0);
}
catch (ArithmeticException e) {
   System.out.println("catch");
}
finally {
   System.out.println("finally");
}
Output
Hi 

No comments:

Post a Comment