jdk 1.4에서의 try-catch-finally 와 return

JAC_061: Do Not Return From Inside A try Block (High)
Feedback
Code leaves the try block when it finishes normally, when an exception
is thrown or a return, break or continue statement is executed. When a finally block
exists, it will always be executed. This means that a return in a try block is not
guaranteed to be the normal flow of the code! Putting a return statement in a try
block might lead a developer to think that the finally block will not be executed.

Note
See also rule JAC_016: Use A Single return Statement (Normal).

JAC_062: Do Not Return From Inside A finally Block (High)
Feedback
Avoid returning from a finally block – this can discard exceptions.

WRONG


public void bar() {
    try {
        throw new JMSException("My Exception");
    } catch (JMSException e) {
        logger.log(Level.WARNING, "JMS Problem", e);
        throw e;
    } finally {
        return;
    }
}

RIGHT


public void bar() {
    try {
        throw new JMSException("My JMS Exception");
    } catch (JMSException e) {
        flag = "NOK";
        logger.log(Level.WARNING, "JMS Problem", e);
        throw e;
    } finally {
        // cleanup here
    }
}

이런 이유로

(1)


try {

...

return; // ERROR
}

(2)


try {
...
}

finally {
...
return; // ERROR
}

이렇게 바뀌었습니다.. 에러가 나서 순간당황하게 되죠. (저도 그랬고..)

이제부턴,


try {
...
}

catch(...) {
...
}

finally {
...
}

return ...;

이게 정석이되는 듯..

java coding convention을 올린건 이와같은 유사한 문제에 대해 명쾌하게 해석을 하고 있기 때문입니다. 처음 공부하던 00년 01년의 java coding convention이란 pdf파일과는 차원이 다를 정도로 많이 발전했네요.. 더구나 놀라운건 java.net의 코딩 컨벤션에서 보면 메뉴가 한국어로 나온단 것..

Similar Posts:

Post a Comment

Your email is never published nor shared.