[an error occurred while processing this directive]

Example to show Finally exception in java


Finally block are the block, that executed when the try block exits. This block executed even after the unexpected exception occured.The Run time always execute the expression in finally block irrespective of the try block. This block is known for recovering and preventing from resources leak.On closing of the file and recovering of a file, you need to place the expression in the finally block.

Understand with Example.

In this Tutorial we want to describe you a code that helps you to handle finally exceptions. The Finally block succeed when the try block exists and will  executed when an unexpected exception occurs in the code.. The program given below describes how to use the finally block. In this program if the file "girish.txt" does not occurs it will throw File not Found exception. and also executes the finally block of the program.

1)File Input Stream  - This is used to decode the byte and further convert it into a character. stream

Inside the main method the input stream include a  fileinputstream object that store and convert  convert the byte code to a character stream from a file name "girish.txt".In case there is no such file on the name of "girish.txt".The catch block caught the unexpected exception .Later on finally block print the exception.


import java.io.*;

public class FinallyException {

    public static FileInputStream inputStream(String fileName)
            throws FileNotFoundException {
        FileInputStream fis = new FileInputStream(fileName);
        System.out.println("f1: File input stream created");
        return fis;
    public static void main(String args[]) {
        FileInputStream fis1 = null;
        String fileName = "girish.txt";
             try {
            fis1 = inputStream(fileName);
        catch (FileNotFoundException ex) {
            System.out.println("FileNotFoundException occured");
        catch (Exception ex) {
            System.out.println("genreal exception occured");
        System.out.printlnFinallyException.class.getName() " ended");


Output of the program

FileNotFoundException occured
FinallyException ended

Download source code


[an error occurred while processing this directive]