1

I ran into a little problem today where I have a piece of code like this, which made me a little uncomfortable...

   try{
       //stuff...
   } finally {
       //finally stuff
   }

I wonder if such implementation is a good practice in terms of when an exception occurs in the try and is re-thrown to the caller who handles it. Is this equivalent to the code below?

    try{
        //code....
    } catch (Exception e) {
        //handling...
    } finally {
        //finishing up
    }
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
lrl
  • 263
  • 4
  • 18
  • Duplicate of [Difference between try-finally and try-catch](http://stackoverflow.com/questions/2854910/difference-between-try-finally-and-try-catch) – NullPointerException May 15 '13 at 18:23
  • 1
    I looked at that one http://stackoverflow.com/questions/2854910/difference-between-try-finally-and-try-catch but I still kind of confused... maybe – lrl May 15 '13 at 18:30

2 Answers2

5

It's not equivalent, because of the reason you already gave: The exception is still thrown in the first case. And there might be reasons, where you exactly want such a behavior: Close resources, e.g. Streams in finally block, but throw the exception out of the enclosing method, to handle it else where.

Btw., you can also "abuse" try-finally constructs, in case no exception is expected at all:

private StringBuilder buffer = new StringBuilder();

private String getBuffer() {
    try {
            // return current String content of the buffer
            return buffer.toString();
    } finally {
            // assign a new StringBuilder, before method returns
            buffer = new StringBuilder();
    }
}
qqilihq
  • 10,794
  • 7
  • 48
  • 89
  • thanks, in my case it is an 'abuse' as you described it. Nice example by the way... – lrl May 15 '13 at 20:10
2

Not exactly, a try/finally block without catch is the equivalent of

try {
    // ...
} catch (Exception e) {
    throw;
} finally {
    // finishing up
}

Where you just re throw the exception without handling it. Omitting the catch block is good if this is what you intended to do, it improves the code readability.

Dalmas
  • 26,409
  • 9
  • 67
  • 80