Exception Handling
Exception Handling
} }
}
Output:
Exception thrown :java.lang.ArithmeticException: / by zero
Multiple catch blocks
• A try block can be followed by multiple catch blocks. The syntax
for multiple catch blocks looks like the following −
try
{
// Protected code
}
catch(ExceptionType1 e1)
{
// Catch block
}
catch(ExceptionType2 e2)
{
// Catch block
}
catch(ExceptionType3 e3)
{ // Catch block }
• The previous statements demonstrate three catch blocks,
but you can have any number of them after a single try.
• If an exception occurs in the protected code, the
exception is thrown to the first catch block in the list.
• If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the
exception passes down to the second catch statement.
• This continues until the exception either is caught or falls
through all catches.
class UncaughtException
{
public static void main(String args[])
{
try
{
// int a[]=new int[5];
int a=30/0;
}
catch (ArithmeticException e)
{
System.out.println("Exception thrown :" + e);
}
catch(ArrayIndexOutOfBoundsException e1)
{
System.out.println("Exception thrown :" + e1);
}
}
Output:
Exception thrown :java.lang.ArithmeticException: / by zero
Nested try statements
• Sometimes a situation may arise where a part of a block may cause one
error and the entire block itself may cause another error. In such cases,
exception handlers have to be nested. Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
Eg:
class Excep6
{
public static void main(String args[])
{
try
{
try
{
int a[]=new int[5];
a[8]=200;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
int value = 200/0;
}
catch(ArithmeticException e1)
{
System.out.println(e1);
}
}
}