Question

I have discovered possibility of having code "after return" using finally, here is some example:

int foo() {
    BufferedReader br = ...;
    try {
        // cca 20 lines with 4 returns in different if-else clauses etc
        //example:
        if(something) {
            return 0;
        } else {
            return 1;
        }
    } finally {
        br.close();
    }
}

As (in my opinion much more lazy) alternativity to:

int foo() {
    BufferedReader br = ...;
    int toReturn;

    // cca 20 lines with 4 ASSIGMENTS in different if-else clauses etc
    //example:
    if(something) {
        toReturn = 0;
    } else {
        toReturn = 1;
    }

    br.close();
    return toReturn;
}

So, the question is, which is faster, more readable, and yes, in this case, i am really closing a BufferedReader, so is try-finnaly for this or am i using it wrong way?

Was it helpful?

Solution

Without using the try/catch/finally, if an exception is thrown, your BufferedReader won't be closed properly, causing a memory leak, potential unwanted file locking...

Using finally, your BufferedReader will be closed, even if an exception is thrown while processing the try block.

But as your BufferedReader instantiation can also throw an exception, you should include it in your try block:

BufferedReader br = null;
try {
    br = ...;
    // do your stuff
}
catch (Exception e) {
    // handle exception
}
finally {
    if(br != null)
        br.close();
}

If you're using Java 7 or newer, go with the elegant Try-with-resources, as stated by Arnaud.

OTHER TIPS

If there is an exception throws, both your code fail since first case you are not catching exception and second case there are no evidence of handling exception.

finally will execute any way here.

If your BufferedReader get input by file read, in a case which file not found both ways are not useful.

The second one is actually unacceptable. You will not close the buffer in case of exception.

I advise you to use the try-with-resources statement (intended for that purpose):

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    //do what you want with the buffer. It will automatically be closed.
    return;
}

See The try-with-resources Statement

am i using it wrong way?

yes you are. What if say something is a method call and it throws exception, then your br is never closed. While finally makes sure that in any case it will get execute*

`* - there are some conditions where you can avoid finally clause execution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top