Monday, 30 January 2017

Exception Handling

Error and Exception Handling
Mistakes are common when we write a program, these mistakes are called errors or exceptions, and due to these errors a program may produce unexpected results. The error may also cause termination or crash of the program. So it is important to detect and manage error conditions so program can run properly and will not terminate during execution. Errors in the code should be managed such that if some error is there in the code it should give proper error message instead of crashing or termination of the program suddenly.

Type of Errors  
Errors or exceptions in java can be categorized in to two categories.
1.      Compile Time Errors
2.      Run Time Errors
Compile Time Errors: Error such as typing mistakes and other syntax errors are called compile time errors. These errors are detected by the java compiler, it is necessary to fix these errors to compile and run the program.
Common compile time errors are:
Missing semicolon (;) at the end of a statement.
Mismatch of brackets ({…}) when defining a class or method.
Spelling mistakes when typing reserved keywords (identifiers and keywords) of java (clas instead of class).
Incompatible types in initialization of a variable (int x = 33.4, trying to initialize an integer type variable with float value).
Use an undeclared variable (x = 5, x is not declared of any type and trying to initialize it).
Etc.

Run Time Errors: Sometimes program may compile properly but does not display proper output due to logical error; such errors are called run time errors.
Common run time errors are:
Dividing a number by zero.
Trying to access an element which is out of bounds of an array.
Trying to store a different type of value in an array (trying to store character value in integer type array).
 Trying to create an instance of a class into its subclass.
Trying to pass improper parameters (in different order or different type of parameter) in a method.
Trying to create an array of size less than or equal to zero.
Improper type cast, converting invalid string into number.
Etc.
Exceptions
Basically exceptions are runtime errors. When java compiler encounters any run time error it creates an exception object and throws it. If exception is not handled properly java compiler will display an error message and terminate the program. If we want to execute rest of the code even after exception appeared, we will need to handle the exception by trying and catching. We will need to catch the exception thrown by compiler and display proper error message to take correct action. This process is called exception handling.
Error handling code is basically consists of two parts one is to detect an error and throw exception and other is to catch the exception and take proper action to handle the exception.
Exception Handling
To catch an exception in java we use try/catch block.
Example:
try
{
                     //Code
                     //Code       
              } catch (ExceptionType e) {
                     //Code
                     //Code                           
       }
If any statement of code inside try block throws an exception of class  ExceptionType specified in catch clause, then compiler skips rest of the code in the try block and executes the exception handler code in the catch block. If no exception is encountered in the try block then catch block will be skipped.
Example:
public class ExceptionHandling {
       public static void main(String[] args)
       {
              int result1, result2;
              int x = 5, y = 5, z = 0;
             
              try
              {
                     result1 = x/y;
                     System.out.println("x/y = " + result1);
                     result2 = x/z;
                     System.out.println("x/y = " + result2);
              }
              catch(ArithmeticException e)
              {
                     System.out.println("Arithmetic Exception:  " + e);
              }
              System.out.println("End of program");
       }

}
The output of this program is:
x/y = 1
Arithmetic Exception:  java.lang.ArithmeticException: / by zero
End of program
In try block first statement result1 = x/y executed successfully and displayed result. The statement  result2 = x/z is not executed because value of x is 5 and value of z is 0 means this statement is trying to divide a value with 0 which is an error (exception). So this statement is not executed and control shifted to catch block due to exception. The statement in catch block is executed and the string of exception is also printed which is value of e (java.lang.ArithmeticException: / by zero), it is showing divide by zero error. ArithmeticException is an exception type predefined in java.
Multiple Catch Blocks
It is possible that a statement in try block may throw more than one type of exception. To handle this situation we can use a sequence of catch blocks one for each type of exception.
Example:
public class ExceptionHandling {
       public static void main (String args [])
       {
              int myArray[ ] = new int [5];
              try
              {
                     for (int i = 0; i <5; i++)
                     {
                           //do nothing
                     }
                     for (int i = 0; i <5; i++)
                     {
                           myArray[i] = i/ i;
                     }
              }
              catch (ArrayIndexOutOfBoundsException e)
              {
                     System.out.println ("Array out of bound ");
              }
              catch (ArithmeticException e)
              {
                     System.out.println ("Zero divide error");
              }
       }

}
The output of this program is:  Zero divide error
In this example we have used two catch blocks  for ArrayIndexOutOfBoundsException and ArithmeticException. Similarly we can use multiple catch blocks for different exception types as per our requirement.
Finally Block
 We can use finally clause (after try and catch) to make sure that a line of code runs whether exception occurs or not. When code throws an exception, it will stop execution of rest of the code and exit the method. But in a situation when a method acquired some resources and that needs to be free before exiting the code there is problem. To handle this situation java provides finally clause.  
Example:
public class ExceptionHandling {
       public static void main(String args[])
       {
              try
              {
                     System.out.println("Try Block before the error.");
                     System.out.println(1/0);
                     System.out.println("Try Block after the error.");
              }
              catch(ArithmeticException e)
              {
                     System.out.println("Catch Block");
                     System.out.println("A Stack Trace of the Error:");
                     e.printStackTrace();
                     //e.getMessage();
                     System.out.println("The operation is not possible.");
              }
              finally
              {
                     System.out.println("Finally Block");
              }
             
              System.out.println("End of Program");
       }

}
The output of the program is:
                        Try Block before the error.
              java.lang.ArithmeticException: / by zero
              at ExceptionHandling.main(ExceptionHandling.java:10)
              Catch Block
              A Stack Trace of the Error:
              The operation is not possible.
              Finally Block
              End of Program

The finally statement will always execute whether exception occurs or not. So the code we want to execute in both the conditions we write in finally block.

Throwing Exception
Sometimes we need to throw our own exception. We can throw our own exception using throw statement. Generally we throw exception when user enters wrong input to a program. Throw statement terminates normal flow of the program and prevents execution of subsequent code.
Example:
       public class ExceptionHandling {
       static void myThrowMethod()
       {
              try
              {
                     System.out.println ("Throwing Exception ");
                     throw new IllegalStateException ();
              }
              catch (NullPointerException e)
              {
                     System.out.println ("Catch method inside myThrowMethod ");
              }
       }
       public static void main (String args[ ])
       {
              try
              {
                     myThrowMethod();
              }
              catch(IllegalStateException e)
              {
                     System.out.println("Exception Found:"+e);
              }
       }
}

The output of this program is:
       Throwing Exception
       Exception Found:java.lang.IllegalStateException

We have created a method  myThrowMethod(); in main class. The body of this method contains a try block which is throwing an exception using throw new IllegalStateException (); statement.  IllegalStateException is a predefined java exception. When we call method myThrowMethod(); from main() method, it executes try block of the myThrowMethod() method which is nothing but an exception, so control comes out of the method. It is just like this method has encountered an exception so control will go into the catch block of main() method.

We can create our own class to throw an exception.

Example:

 class MyException extends Exception {
      
       MyException(String message)
       {
              super(message);
       }
}


public class ExceptionHandling{
      
       public static void main (String args[ ])
       {
              int a = 2; int b = 1000;
             
                    
              try
              {
                     float c = (float) a/ (float)b;
                     if(c<0.01)
                     {
                           throw new MyException("Number is small");
                     }                   
              }
              catch (MyException e)
              {
                     System.out.println ("Catch MyException! ");
                     System.out.println (e.getMessage());
              }
              finally
              {
                     System.out.println ("Finally executed ");
              }
             
       }
}
The output of this program is:
       Catch MyException!
       Number is small
Finally executed
In this example we have created our own class MyException which extends Exception. When exception is thrown an instance of this class is created and a string is passes to this class.
Throws statement
A throws statement is used by a method to specify which type of exception this method will throws.
Example:
       public class ExceptionHandling{
      
       static void myThrowMethod ( ) throws ClassNotFoundException
       {
              System.out.println ("In throwMethod ");
              throw new ClassNotFoundException ( );
       }
       public static void main (String args [ ])
       {
              try
              {
                     myThrowMethod ( );
              }
              catch ( ClassNotFoundException e)
              {
                     System.out.println ("Exception thrown by myThrowMethod  :" +e);
              }
       }
       }
 The output of this program is:
       In throwMethod
Exception thrown by myThrowMethod  :java.lang.ClassNotFoundException





No comments: