Use of finally Clause in java
Use of finally Clause in java |
•finally block may be added immediately after try block or after the last catch block.
•finally block in general used to perform house keeping operations such as closing files or releasing system resources.
•Finally block when present is guaranteed to execute regardless of whether an exception is thrown or not.
•If you want then finally block can be used to handle any exception generated within a try block.
finally clause Syntax
EXAMPLE 1
try {
…………………..
……………………..
…………………….
} finally
{ ……………..
……………..
……………. }
EXAMPLE 2
try
{ …………………..
……………………..
…………………….
}
catch(……….)
{ ……………. }
catch(………..)
{
…………….
}
…..
…..
finally
{
…………..
…………..
}
Example(finally clause)
class ex10 {
public static void main(String args[])
{
int a=10; int b = 20;
try { int b1=Integer.parseInt(args[0]);
int x = a/(a-b1); try { int y = b/(b-b1);
}
finally { System.out.println("Inner Block executed");
}
}