0

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?

Kasinaat 007
  • 124
  • 14
freakydavid
  • 114
  • 6
  • 3
    Because [catching all Exceptions is almost always a bad idea](https://stackoverflow.com/questions/2416316/why-is-the-catchexception-almost-always-a-bad-idea). – Michael May 23 '18 at 13:27
  • hi :) without the finally block you are not sure whether `out` is closed or not if any exception occurs. and more than that, with your solution, it isn't closed at all ;) – Julien May 23 '18 at 13:28
  • 1
    @Julien I suppose they're saying that out.close() would be in the `finally` block. I don't know why they left that out. – Michael May 23 '18 at 13:29
  • @Michael it's exactly what I mean :) I've completed my comment this way. – Julien May 23 '18 at 13:30
  • you should use java 7 [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) to automatically close resources – Sharon Ben Asher May 23 '18 at 13:30
  • out.close() would execute even if we write it without the finally block in the above code after the try-catch block – freakydavid May 23 '18 at 13:31
  • You haven't caught all exceptions. There are also `Errors` and `Throwables.` And in any case you never want to do that. You want to let the caller handle them. – user207421 Jun 14 '18 at 07:14

2 Answers2

4

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17
0

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.

Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47