Wednesday, 28 September 2011

Exception Handling In Java

                                            Exception Handling In Java   

        Before going to know how to handle an exception in java lets see what happen when we won't handle the exception properly.
       
          See this example :

 
              class example
              {
                  public static void main(String a[])          
                  {
                         int d=0;
                         int n=45/d;
                         System.out.println("n="+n);
                     }
                }

                 When we execute this program the default exception handler will displays a error message as below and  terminate the program abraptly.

 
                  Error :
                         java.lang.ArithmeticException : / by zero  at example.main(example : 6)

 
                To overcome from this kind of abnormal termination we have to handle an exceptions.

 
Exception :
                  Exception is a condition that caught under runtime circumstances of the program.

 
Exception Handling :
                  When an exception is caught in the execution of program, it has to managed by exception object properly. This task is called as Exception Handling.

 
Exception Types :
                 
                     Both Exception and Error classes are the subclasses of the class Throwable.
                     Exception class defines the exception that caught under normal circumstances of the program.
                                 Ex : DivisionByZero
                                        InvalidArrayIndexing
                     Error class is used to indicate errors having to do with runtime environment itself and it cannot be handled by the program.     
                                 Ex : StackOverFlow

 
Types :
  • ArithmeticExceptions
  • ArrayOutOfBoundsExceptions                       
  • IndexOutOfBoundsExceptions
  • NegativeArraySizeExceptions
  • NullPointersExceptions
  • NumberFormatExceptions
  • IOExceptions
 
There are 5 keywords used to manage the exception handling :
  • try
  • catch
  • throw
  • throws
  • finally

 
try and catch Exception Handling :

             The try block can have one or more statments that could generate an exception, the remaining statement in a block are skipped and the execution jumps to the appropriate catch block.
             The try block must be followed by atleast one catch statement; otherwise the compilation will occur.
             The catch statement works like a method definition. It has single parameter which is thrown as exception object by try block.
             If the catch parameter matches with the type exception object, then the exception is caught and the statements in catch block will be executed. Otherwise the exception is not caught and the default exception handler will cause the execution to terminate.

 
Syntax :
----
----
try
{
stmts;
}
catch(Exception_type e)
{
stmts;
}
----
----
    
Multiple Catch Statements :
            When an exception is created in a try block, the first catch statement whose parameter matches with the exception object will be executed and remaining statements will be skipped.

 
Syntax :
----
----
try
{
stmts;
}
catch(Exception_type1 e)
{
stmts;
}
catch(Exception_type2 e)
{
stmts;
}
.
.
.
.
catch(Exception_typeN e)
{
stmts;
}
----
----

 
Finally Statements :
         Java supports finally statements that is used to handle an exception which is not caught by any of the previous catch statements.
         Its used to handle any exception generated within a try block.
         It can be added immediately after the try block or after the last catch block.
         When a finally block is defined, this is guaranteed to execute, regardless of whether or not an exception is thrown.

 
Syntax :

 
try
{
stmts;
}
finally
{
stmts;
}

 
   (OR)

 
try
{
stmts;
}
catch(Exception_type1 e)
{
stmts;
}
catch(Exception_type2 e)
{
stmts;
}
.
.
.
.
catch(Exception_typeN e)
{
stmts;
}
finally
{
stmts;
}

 
Example :

 
import java.io.*;
class Err4
{
public static void main(String a[])
{
int a[]={5,10};
int b=5;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Error");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong Data Type");
}
finally
{
int y = a[1]/a[0];
System.out.println("Y="+y);
}
}

 
Output :
 ArrayIndexError
 Y=2

Throwing our own exceptions :
               To throw our own exceptions throw keyword is used.

Syntax :
                throw new Throwable_Subclass:
Example :
                throw new ArithmeticException();

Throws :
               If an exception is causing in a method, it couldn't be handled. The throws keyword is used to handle this exception with including exception type. 

Syntax :
               type method_name(parameter_list)throws Exception_list
                {
                      //Body of method;
                 }
Example :
                void put()throws IOException
                 {
                      System.out.println("Enter the string : ");
                       s1=br.readLine();
                       System.out.println("Length :"+s1.length());
                  } 

 
                  
     

 

 

 

 

 

 

 

 

 

 
 

 

 

No comments:

Post a Comment