Saturday 22 February 2014

try block

Syntax
try {
   //code
}
catch and finally blocks . . .
The first step to handle the exception is enclose the error prone code in the try block. A try blcok must have at least one catch or finally block. Other wise compiler throws an error.

Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(" I don't have any catch or finally blocks associated with me");
  }
 }
}
   
Above program, doesn't have any catch or finally block associated with it. So when you tries to compile the program, compiler throws the below error.

ExceptionEx.java:4: error: 'try' without 'catch', 'finally' or resource declarations
try{
^
1 error

try nested inside a try
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println("I am enclosing another try inside me");
   try{
    System.out.println(10/0);
   }
   catch(ArrayIndexOutOfBoundsException e){
    System.out.println("inside catch block " + e);
   }
  }

  catch(Exception e){
   System.out.println("Outside catch block " + e);
  }
 }
}
 
Output
I am enclosing another try inside me
Outside catch block java.lang.ArithmeticException: / by zero

As you observe the program, try has try nested in it. “10/0” is called in inside try block, which has catch block associated with it. But the catch block for the inner try block handles ArrayIndexOutOfBoundsException only. So while executing, the catch correspond to the outer block is executed.


Handling Exceptions                                                 catch block                                                 Home

No comments:

Post a Comment