freakydavid
freakydavid

Reputation: 114

What is the need of finally block in java?

Consider the code from java docs below:

public void writeList() {
    PrintWriter out = null;

    try {
        System.out.println("Entering" + " try statement");

        out = new PrintWriter(new FileWriter("OutFile.txt"));
        for (int i = 0; i < SIZE; i++) {
            out.println("Value at: " + i + " = " + list.get(i));
        }
    } catch (IndexOutOfBoundsException e) {
        System.err.println("Caught IndexOutOfBoundsException: "
                           +  e.getMessage());

    } catch (IOException e) {
        System.err.println("Caught IOException: " +  e.getMessage());

    } finally {
        if (out != null) {
            System.out.println("Closing PrintWriter");
            out.close();
        } 
        else {
            System.out.println("PrintWriter not open");
        }
    }
}

"finally block executes whether an exception happens or not or an exception is not handled" this is the definition I see everywhere.

My Question is What if I replace two catch blocks with one catch block saying

try {
        System.out.println("Entering" + " try statement");

        out = new PrintWriter(new FileWriter("OutFile.txt"));
        for (int i = 0; i < SIZE; i++) {
            out.println("Value at: " + i + " = " + list.get(i));
        }
    } catch (Exception e) {
        e.printStacktrace()
    }

Above code handles all the exceptions. So, why do we need a finally block here? Instead of doingsomething in finally block I can write that outside the try-catch block,Both are same.

Why do we need finally block here?

Upvotes: 0

Views: 1480

Answers (2)

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5591

As per oracle Documentation:

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

For detail read this article.

Now answer to your below question:

Now the above code handles all the exceptions. So, why do I need a finally block here? Instead of writing something in finally block I can write that outside the try-catch block,Both are same.

Suppose you are re-throwing an exception from a catch block, in such a condition non of the codes after that catch block will execute but if you add a finally block all the codes inside finally block will execute before re-throwing of the exception from the catch block.

Upvotes: 4

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

you don't need the finally block. However, this solution is considered bad practice.

The reason is that now, the catch phrase must remain exactly as it is in order to ensure the resource is properly closed. Now imagine if another programmer (or even yourself) needs to modify this piece of code somewhere in the not-so-distant future.

by the way, since java 7, the most safe way to ensure resources are properly closed, is to use try-with-resources.

Upvotes: 0

Related Questions