The Finally block in Java

Finally blocks are executed once the try block exits. This block executes even after the unexpected exceptions has occurred. Irrespective of the try block, the expression in finally block is always executed. This block is in-built with the capability of recovering loss and preventing leak of resources. On closing and recovery of a file, the expression should be placed in the finally block.

 

import java.io.*;

public class FinallyException

{

public static FileInputStream inputStream(String fileName)throws FileNotFoundException

{

FileInputStream fiss=new FileInputStream(fileName);

System.out.println("f1:FileInput Stream created");

return fiss;

}

public static void main(String aa[])

{

FileInputStream fis1=null;

String fileName="xcnotes.txt";

try

{

fis1=inputStream(fileName);

}

catch(FileNotFoundException ex)

{

System.out.println("FileNotFoundException occurred");

}

catch(Exception ex)

{

System.out.println("General exception occurred");

}

System.out.println(FinallyException.class.getName()+ "ended");

}

}

Output.....

Finally block in Java

Explanation…

The success of the finally block depends upon the existence of the try block and will execute only when an unexpected exception arises in the code.

In above example….

1)First, java.io.* package imported.

2)Then, a class FinallyException class is created.

3)In the class FinallyException,

   a)The FileInputStream inputStream(String filename)method is called with the string filename in it, and is declared public and static.

b)The FileNot FoundException exception is thrown using the throws keyword.In this exception,

     i)A new FileInputStream object fiss is created.

     ii)Then,the f1:File inputstream created statement is printed on the screen.

   iii)Also, the value of fiss is returned using the return statement.

c)The main() method of the class is called. In the main(),

   i)The FileInputStream fis1 is assigned the value null.

   ii)The String filename is assigned the string xcnotes.txt.

   iii)In the try block, fis1 is assigned the value in inputStream, that is, filename.

   iv)Then, the catch block is used to catch the FileNotFound ex exception. In the catch block, the FileNotFoundException occurred statement is printed on the screen.

Second catch block is used to catch Exception ex exception. In this catch block, The general exception occurred statement is printed on the screen.

At last, the getName(0 method is called to get the name of FinallyException, and prints it on the screen.