Try-Catch

Exception handler provided by java environment terminate the program abnormally. In order to avoid that situation we have to provide our own handler. try-catch construct is used to provide exception handler.


Syntax :

try 
{
< code that can generate exception >
}
catch(<type of exception> e)
{
< code which will be executed when exception occurred >
}

Program without exception handler

Example :


 class exp
{
public static void main(String arg[])
{
int b=0;
int a=4/b;
System.out.println("a:"+a);
System.out.println("End of program");
}
}

In above program statement int a=4/b; is cause of exception. In try block we will write the statement which can generate an exception.



Program with exception handler

Example :


 class exp
{
public static void main(String arg[])
{
int b=0;
try
{
int a=4/b;
System.out.println("a:"+a);
}
catch(ArithmeticException ae)
{
System.out.println(ae);
}
System.out.println("End of program");
}
}
/* Output:
java.lang.ArithmeticException: / by zero
End of program
*/


In above program when exception is generated , Catch block with appropriate exception will get executed. After exception generation, try block execution is halted and control of execution is transferred to catch block.

Every catch block specify a exception for which they will provide exception handling mechanism. In above program there is only one catch block for ArithmeticException . If in try block other exception is thrown in that case catch block won't handled other exception.

A try block can have multiple catch. In case if there is multiple catch block then catch for thrown exception will be

Program with multiple catch


 class exp
{
public static void main(String arg[])
{
int b=0;
try
{
int a=4/b;
System.out.println("a:"+a);
}
catch(ArithmeticException ae)
{
System.out.println(ae);
}
catch(ArrayIndexOutOfBoundsException a)
{
System.out.println(a);
}
System.out.println("End of program");
}
}
/* Output:
java.lang.ArithmeticException: / by zero
End of program
*/