Finally, Block in Java

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

Java Program to Use Finally Block

import java.io.*;

public class finallyy

{

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”);

}

finally

{

System.out.println(Exception.class.getName()+ “ended”);

}}

}

Finally Block in Java

Explanation…

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

In the 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(public static FileInputStream inputStream(String fileName)throws FileNotFoundException).

b)The FileNot FoundException(String fileName=”xcnotes.txt”;) exception is thrown using the throws keyword.In this exception,

      i)A new FileInputStream object fiss is created.

     ii)Then, the f1:File input stream 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(FileInputStream fis1=null;).

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

    iii)In the try block(try{}), 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(System.out.println(“General exception occurred”);) is used to catch Exception ex exception. In this catch block, The general exception occurred statement is printed on the screen(catch(Exception ex) {System.out.println(“General exception occurred”);}).

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