Catching Exception:try/catch block

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. In the block preceded by catch, we put the code that will be executed if and only if an exception of the given type is thrown. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:


   //Protected code
}catch(ExceptionName e1)
   //Catch block
 A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.


The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.


public class ExcepTest{

public static void main(String args[]){
        int a[] = new int[2];
        System.out.println("Access element three :" + a[3]);
     }catch(ArrayIndexOutOfBoundsException e){
        System.out.println("Exception thrown  :" + e);
        System.out.println("Out of the block");



This would produce following result:

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

People who read this post also read :


Post a Comment


Twitter Delicious Facebook Digg Stumbleupon Favorites More