The syntax for the usage of try, catch and finally block is
given below.
Listing 1
try
{
………
………
}
catch(exceptionclass obj1)
{
………
………
}
catch(exceptionclass obj2)
{
………
………
}
finally
{
………
………
}
For using an exception handler in an application, the first
step we need to do is to enclose the code that is likely to generate an
exception inside a try block. If an exception occurs in the try block then it
is handled by the exception handler associated with it. For associating an
exception handler to the try block, we need to have one or more catch blocks
after the try block where each catch block acts as an exception handler and can
handle the type of exception indicated by its arguments. Exception handlers can
be used to print an error message when an exception occurs, to halt the
program, to redirect the error to a higher level handler using chained
exception, to write code for recovering from the error, etc. The finally block
is the block which is always executed when the try block exits which ensures
that the finally block is executed even when an unexpected exception occurs. It
acts as the appropriate place for writing the clean up code.
Listing 2
class exceptionDemo
{
Random r = new Random();
int a = r.nextInt();
int b = r.nextInt();
int c = r.nextInt();
try
{
c = a / b / c;
System.out.println("Value of c " + c);
}
catch (ArimeticException e)
{
System.out.println("The error is " + e);
}
}