0

Basically I am not really sure what is the correct usage of the finally keyword, I only know the textual definition: Guarantees a code will be executed cause sometimes it doesn't. So I was hoping I could get some directions on this particular code:

Also if the try-catch block to call InputStream#close() is unnecesary

try {
    inputStream = entity.getContent();

    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder sb = new StringBuilder();

    String line = null;

    while((line = br.readLine()) != null) {
        sb.append(line);
        sb.append("\n");
    }

    responseText = sb.toString();
} catch(IOException e) {
    e.printStackTrace();
} finally {
    if (inputStream != null) {
        try {
            inputStream.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}
Luca Tettamanti
  • 10,314
  • 3
  • 29
  • 25
Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206
  • Is this code for Apache HttpClient? (That entity.getContent() looks familiar!) If so, try using EntityUtils.consume(entity) to ensure the connection is released. – Jonathan Pullano Feb 21 '14 at 20:15

6 Answers6

1

You can also use a try-with-resources.

Like so:

try (YourResource resource) {
    //Todo...
} catch(YourSpecificException ex) {
    //Todo...
}

Your resource declared between parantheses will be automatically closed upon exiting the construction.

You can even declare multiple resources in one go, separate them with a semi-colon. It's all in the above link, really.

Reinstate Monica
  • 2,767
  • 3
  • 31
  • 40
  • I'm not a fan of [Pokémon Exception Handling](http://www.codinghorror.com/blog/2012/07/new-programming-jargon.html). Catch what's thrown, let actual errors bubble up. – David Ehrmann Feb 21 '14 at 20:17
  • @DavidEhrmann If you're referring to the generic exception, you're completely right, and I agree. I only put it there as a generic example. In hindsight it might have been giving off the wrong signal. Let me edit it. – Reinstate Monica Feb 21 '14 at 20:19
0

The finally block will always be executed whether the exception has arise from try block or not.So finally block is used as post activity.In the code you are using to close the stream.

Kick
  • 4,823
  • 3
  • 22
  • 29
0

the finally block ensures that no matter what happens during your try( success or exception), it will always run. This is normally used when cleaning up resources, like InputStream or a Socket

The try with resource paradigm cleans this up, but automatically closing things that are Closeable

try( InputStream inputStream = entity.getContent() )
{

}catch(Exception e)
{

}//declared resource in try automatically closed

http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Samhain
  • 1,767
  • 1
  • 12
  • 20
0
try { 
  // Here the guarded area starts


  // Here the guarded area ends
} catch {
  // This block is executed when an exception occurs inside the guarded area

} finally {
  // This block is executed always before leaving try - catch - finally block
  // If there is an exception, then first catch block is executed and then finally
}

The code inside finally block you have is a commonly used structure for closing streams. If a stream was created inside guarded area (inputStream != null), then finally block will close it. If there was an exception before inputStream was created, then finally block is executed, but because inputStream == null, the code inside if statement does not execute.

sergej shafarenka
  • 20,071
  • 7
  • 67
  • 86
0

When try block is executing any exception that occurs will transfer the execution to the catch block then to finally block however if no exception happens in the try the execution of the code will continue after the try to the finally block, here in your code you are trying to use IO resource, which might throws an IO exception if it cannot be occupied by the process then no reference will be assigned to inputStream a finally block must be found to close the IO connection at any case if the resource was occupied or if it is null then nothing, remember finally will always be executed at any case, it is best for closing connection to databases and other resources to release memory too sometimes.

Mahmoud Hashim
  • 550
  • 5
  • 13
0

The times I've used finally are generally...

  • resource handling (IO, DB connections, sockets)
  • Concurrency (lock releasing, guaranteed counter changes)
  • finalization (try { } finally { super.finalize(); })
  • record keeping of states
David Ehrmann
  • 7,366
  • 2
  • 31
  • 40