Monday, 14 November 2011

Java Exception Handling



When an exception condition arises, an object representing that exception is created and thrown in the method itself, or pass it on. After throw the exception is caught and processed.
Java exception handling is managed by five keywords:


  1. try :-     The program statements those you want to test are put in try block.
  2. throw:- If exception is generated in try block then it can be thrown by throw.
  3. catch :- To catch the exception which is thrown by try block , catch is used.
  4. finally :-Any code that absolutely must be executed before a method returns, is put in finally block.
  5. throws :-Any exception that is thrown out of a method must be specified by throws keyword        .

Syntax:

try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// ...
finally
{
// block of code to be executed before try block ends
}

According to the above syntax The portion of program  wanted to be tested is put inside try block. If exception is generated then control goes to matching catch block. ExceptionType is the type of exception that has occurred.The statements after throw will not executed. After executing catch execution continues from the statements after catch block. The type of the object that thrown must be matched with the type of the object that catched in catch block.Try block must have related calch block. The finally block will execute whether or not exception is generated or not.


Using try and catch

Although the default exception handler provided by the Java run-time system is useful for debugging, you will usually want to handle an exception yourself. Doing so provides two benefits. First, it allows you to fix the error. Second, it prevents the program from automatically terminating.

The try and catch block is used to handle the exception. The code which may generate an error that need to put in try block and according to the arrived error it must be catched by the catch block.

Ex,

class Exc1
{
     public static void main(String args[])
      {
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
     }
}

Multiple catch Clauses

It is possible to have several catch blocks for the same try-block. This is usually the case if the code inside the try-block throws more than one type of exception. . When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are  by passed, and execution continues after the try/catch block.

But, multiple catch blocks can also be used in the case where all the exceptions thrown inside the try-block are the same type or subclasses of that type
Ex,
try
{
    //call some methods that throw IOException's
} 
catch (FileNotFoundException e)
{
} 
catch (IOException e)
{
}

Remember that the first catch-block a thrown exception matches will handle that exception. In this example all IOExceptions are being handled by the catch(IOException e) except for FileNotFoundException. The fact that FileNotFoundException is a subclass of IOException gives us the choice of either treating all IOExceptions the same, or catch some of IOExceptions subclasses individually, as is done in the code example above. If the catch(FileNotFoundException e) block is removed any FileNotFoundException will be caught by the catch(IOException e) block, since FileNotFoundException is a subclass of IOException.


// Demonstrate multiple catch statements.
class MultiCatch
{
  public static void main(String args[])
  {
    try
      {
      int a = args.length;
      System.out.println("Number of argument = " + a);
     
      int b = 42 /a;
      System.out.println("ans : "+b);
      int c[] = { 1 };
      c[4] = 99;
      
    }
   catch(ArithmeticException e)
     {
      System.out.println("Error : Divide by 0: " + e);
     }
    catch(ArrayIndexOutOfBoundsException e)
     {
     System.out.println("Error: Array index oob: " + e);
     }
   catch(Exception e)
     {
         System.out.println("Error"+e);
     }   


    System.out.println("After try/catch blocks.");
  }
}


Nested try Statements

The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception.


// Demonstrate  nested try statements.
class NestTry
 {
  public static void main(String args[])
   {
      // Outer try
    try
     {
      int a = args.length;

      // If no command line args are present,
        
      int b = 42 / a;

 System.out.println("a = " + a);
       // Inner try        
  try
   {
      // nested try block
     // If one command line arg is used,
         
    if(a==1)
     { 
         a = a/(a-a); // division by zero
     }

        // If two command line args are used
         
    if(a==2)
     {
int c[] = { 1 };
c[4] = 99; // generate an out-of-                                 boundsexception
      }
    } // Innrer try
     catch(ArrayIndexOutOfBoundsException e)
          {
              System.out.println("Array index out-of- bounds: " + e);
      }

    } //Outer try
   catch(ArithmeticException e)
    {
      System.out.println("Divide by 0: " + e);
    }
   catch(Exception e)
     {
        System.out.println("Error " +e);
      }
  }
}

Prepared by : Ruchita Pandya

No comments:

Post a Comment