Exception Handling in JAVA 3
Multiple catch blocks
A try block can be followed by multiple catch blocks. You can have any number of catch blocks after a single try block.If an exception occurs in the guarded code the exception is passed to the first catch block in the list. If the exception type of exception, matches with the first catch block it gets caught, if not the exception is passed down to the next catch block. This continue until the exception is caught or falls through all catches.
Example for Multiple Catch blocks.
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
catch(Exception ex)
{
System.out.println("any other exception");
}
}
}
Output : divide by zero
NOTE: At a time only one Exception is occured and at a time only one catch block is executed.
Example for Unreachable Catch block
While using multiple catch statements, it is important to remember that exception sub classes inside catch must come before any of their super classes otherwise it will lead to compile time error.
class Excep
{
public static void main(String[] args)
{
try
{
int arr[]={1,2};
arr[2]=3/0;
}
catch(Exception e) //This block handles all Exception
{
System.out.println("Generic exception");
}
catch(ArrayIndexOutOfBoundsException e) //This block is unreachable
{
System.out.println("array index out of bound exception");
}
}
}
Output : Compile-time error
NOTE: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception.
No comments:
Post a Comment
Hai , Post your comment . (required, Bugs, Errors )