Server/Java
헷갈리는 Java Exception 호출 순서 정리
selfstarter
2020. 7. 22. 21:00
헷갈리는 Java Exception 호출 순서 정리
항상 헷갈려서해서 까먹지 말라고 정리한다
아래는 파일 쓰기 예제이고 파일 쓰기 성공이든 실패든 output stream을 닫도록 했다.
그런데 Exception 시 error message를 리턴하도록 했다.
이 때 text를 무조건 null로 줘서 Exception이 나는데, finally에서 stream을 닫을 수 있을까?
정답은 닫을 수 있다. finally는 try catch문이 끝나기 전에 무조건 실행된다고 생각하면 된다.
그러므로 아래 예제에서 순서는 try문 실행 -> catch문 실행(return 빼고 모든 코드 실행) -> finally 실행 -> return 실행 순이다
public class TestMain {
public static void main(String[] args) {
System.out.println("value:"+setFileText("./test.txt", null));
}
public static String setFileText(String filePath, String text) {
FileOutputStream output = null;
try {
File newFile = new File(filePath);
output = new FileOutputStream(newFile);
output.write(text.getBytes());
} catch (Exception e) {
System.out.println("error Exception!"+e.getMessage());
return e.getMessage();
} finally {
System.out.println("finally");
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}
System.out.println("success");
return text;
}
}
비슷한 예제로 여기서는 실행순서가 어떻게 될까?
정답은 try문 안에서 return 까지의 코드가 실행되고 finally가 실행되고 마지막에 try문의 return이 실행된다
이제 까먹지 말자!!
try {
System.out.println("실행");
return "여기는 try문";
} catch (Exception e) {
System.out.println("error Exception!"+e.getMessage());
return e.getMessage();
} finally {
System.out.println("finally");
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}