質問

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
    }
役に立ちましたか?

解決

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();
    }
}

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top