문제

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