Pageviews

Wednesday 19 June 2013

Keywords used in Exception handling in Java

by Unknown  |  in Exception handling at  Wednesday, June 19, 2013

Exception handling in Java uses five keywords,unlike C++ which uses 3 keywords i.e. try,catch,throw.Java uses 5 following keywords to handle all types of Exceptions.


  • try
  • catch
  • throw
  • throws
  • finally


1.try block:In the try block,the code which we know that would create exceptions are written in try block.It must be used within the method and it must be followed by finally or catch block.

Syntax:           
            try
      {
       The code that may generate an exception is placed in this block.
        } 


 2.catch : A exception which is thrown by try block must be brought either in catch block or finally block.Once the exception is found in the try block,it is always by the Catch block.

        Syntax:            


 catch(Exception_name objectname)
{
 Statements/ error to display to user when exception occour.
  }


3 throw: Whenever an exception occur,throw block throws the exception to the catch block. Each exception that occur must be caught, the type of exception generated is caught by the catch block of that particular exception, catch block is declared below the try block.

           Syntax:       


 try
 {
 The code which may generate an exception is placed in this block.
 } 
 catch(Exception_name objectname)
{
 Statements to display to the user when an exception will occur.

  }   

4 throwsthrows keyword gives a method flexibility of throwing an Exception rather than handling it. with throws keyword in method


5 finally : This block executes in every situation even the exception occur or not.finally create a block of code that will be executed after a try catch block is executed completely. If an exception is thrown, finally block will execute even if no catch statement matches exception.


Syntax: finally
{
Block of statements which are to be executed
}

Here is the simple program to explain these keywords:

WAP in Java to implement Exception handling

import java.io.*;    //This package is imported when we use Exception handling
class excep2{
public static void main(String args[])
{
try                                                                      //try block
{
int r[]=new int[5];
r[7]=10;
System.out.println("The array is"+r[7]);
}
catch(ArrayIndexOutOfBoundsException exc )                //catch block
{
System.out.println("You are specifying an Array Index which is out of Bound");
}
finally                                                                             //finally block
{
System.out.println("Please check your array size");
}
}
}


The output goes here:


Exception handling























0 comments:

Proudly Powered by Blogger.