126.
executed in case an exception occurs should be placed within the
catch block. You also need to specify
the type of exception that
you wish to catch. You can specify multiple catch blocks for
different types of exceptions.
Following the catch block, you can
specify the finally block. Here, you
need to put in code that you
need to be executed irrespective of whether an exception is
thrown or not. The catch and
finally blocks are optional, but you
need to have either one of them.
The following code demonstrates the try–catch–finally statement:
try {
// Code to be monitored for exceptions
}
catch (ExceptionType 1) {
// Instructions to follow if an exception occurs
}
catch (ExceptionType 2) {
// Instructions to follow if an exception occurs
}
catch (ExceptionType n) {
// Instructions to follow if an exception occurs
}
finally {
// this block is definitely executed even if an
exception is thrown or not
}
What will be the output of the following code snippet?
public class MyClass1 {
public static void main(String abc[]) {
try {
int no;
no = 52 / 0; //Line 1
} catch (
ArithmeticException e) { //Line 2
System.out.println(“ArithmeticException”);
} catch (ArrayIndexOutOfBoundsException e) { //Line 3
System.out.println(“Array Out Of Bound”);
} catch (Exception e) { // any other exception //Lin2
4
System.out.println(“Sorry Unhandled Exception”);
} finally { // this will be executed //Line 5
System.out.println(“I am done!”);
}
System.out.println(“Thank You!!”); //Line 6
}
}
}
Answer:
This code prints the following output:
ArithmeticException
I am done!
Thank You!!
Line 1 causes an ArithmeticException.
This is caught by the
ArithmeticException catch block at Line 2 which prints the
text
ArithmeticException. Since
finally block is always
executed, irrespective of whether an error occurs or not, the
control then transfers to the finally block at Line 5
and prints I am