일반적인 경우 문제가 되지 않겠지만,
예를 들어 두 개의 선언된 Object가 있고 그 Object 모두에 대해 Exception을 Throw하는 Method를 호출하는 경우를 예상해보자.
그럼 그 두 Object의 Method에 대해 catch를 할 것이고
finally Block에는 Release하는 Code가 들어갈 것이다.
그런데 대개의 경우 Release하는 Code 또한 관련 Exception을 Throw하는 것이 일반적이다.
따라서 Release Code에서 catch를 하게 될 것이고
Code를 줄일 목적으로 두 개의 Release Code를 하나로 묶어 catch를 하게 된다면
그 때 바로 이 경고를 보게 될 것이다.
즉, 이는 아래의 Sample Code에서 처럼,
finally Block 내 두 개의 Release Code 중 첫 번째 Code에서 Exception이 발생했을 경우
나머지 하나(두 번째)의 Object에 대한 Release Code를 실행할 수 있을 것이란 보장을 할 수 없기 때문이다.
왜냐하면, 첫 번째 Code에서 Exception이 발생하면 두 번째 Release Code를 실행하지 못 하고 catch Block으로 갈 것이기 때문이다.
따라서 이를 알리기 위한 똑똑한 경고라 하겠다.
"Potential resource leak: 'xxx' may not be closed"를 발생시키는 Code
옳은 Exception Handling...try {// do something with br and bw;} catch(Exception e) {e.printStackTrace();} finally {try {if(br != null) {br.close();br = null;}if(bw != null) {
bw.close();bw = null;}} catch (IOException e) {e.printStackTrace();}}
BufferedReader br = null;BufferedWriter bw = null;try {
// do something with br and bw;} catch(Exception e) {e.printStackTrace();} finally {if(br != null) {try {br.close();br = null;} catch (IOException e) {e.printStackTrace();}}if(bw != null) {try {bw.close();bw = null;} catch (IOException e) {e.printStackTrace();}}}
위 Code에서 보는 바와 같이 finally Block내 두 개의 Object Release를 위한 Code별로 Exception을 Handling하고 있다.
댓글 없음:
댓글 쓰기