The finally block is always executed, regardless of whether or not an exception is thrown. It is recommended for actions like closing file streams and releasing system resources. Writing the finally block for try-block is optional unless there is no catch-block. If no exception occurs during the running of the try-block, all the catch-blocks are skipped, and finally-block will be executed after the try-block.
The finally block may be added after the catch block, or after the last catch block.
try Statements that may generate the exception } Statements to be executed before exiting exception handler } Moves to finally block but does not handle the exception | try Statements that may generate the exception } { Statements to process the exception ‘a’ } …. Statements to be executed before exiting exception handler } Handles the exception and moves to finally block |
class Test
{
public static void main(String as[])
{
int a=Integer.parseInt(as[0]);
int b=Integer.parseInt(as[1]);
try
{
System.out.println(“Division=”+ (a/b));
}
catch(ArithmeticException e)
{
System.out.println("Please check the Denominator”);
}
finally
{
System.out.println("Inside finally block”);
}
}
}
The above program produces the following output.
Output 1: (No Exception)
D:\java>java Test 6 2
Division =3
Inside finally block
Output 2: (With Exception)
D:\java>java Test 6 0
Please check the Denominator
Inside finally block
0 comments:
Post a Comment