Sometimes because of execution of try block the execution gets break off. And due to this some important code (which comes after throwing off an exception) may not get executed. That
Using finally
• Sometimes
because of execution of try block the execution gets break off. And due to this
some important code (which comes after throwing off an exception) may not get
executed. That means, sometimes try block: may bring some unwanted things to
happen.
• The
finally block provides the assurance of execution of some important code that
must be executed after the try block.
• Even
though there is any exception in the try block the statements assured by
finally block are sure to execute. These statements are sometimes called as
clean up code. The syntax of finally block is
finally
{
//clean
up code that has to be executed finally
}
The
finally block always executes. The finally block is to free the resources.
Java Program [finallyDemo.java]
/*
This is
a java program which shows the use of finally block for handling exception */
class
finallyDemo
{
public
static void main(String args[])
{
int a
10,b=-1;
try
{
b=a/0;
}
catch(ArithmeticException
e)
{
System.out.println("In
catch block: "+e);
}
finally
{
if(b!=
-1)
System.out.println("Finally
block executes without occurrence of exception");
else
System.out.println("Finally
block executes on occurrence of exception");
}
}
}
Output
In catch
block: java.lang.ArithmeticException: /by zero
Finally
block executes on occurrence of exception
Program
Explanation
• In
above program, on occurrence of exception in try block the control goes to
catch block, the exception of instance ArithmeticException gets caught. This is
divide by zero exception and therefore /by zero will be printed as output.
Following are the rules for using try, catch and finally block
1. There
should be some preceding try block for catch or finally block. Only catch block
or only finally block without preceding try block is not at all possible.
2. There
can be zero or more catch blocks for each try block but there must be single
finally block present at the end.
Object Oriented Programming: Unit III: Exception Handling and Multithreading : Tag: : with Example Exception Handling Java Programs - Using finally
Object Oriented Programming
CS3391 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation