try-finally 문제점
package exam;
public class TryFinally {
public static void main(String[] args) throws Exception {
TestResource testResource = new TestResource();
try {
testResource.firstMethod();
} finally {
testResource.close();
}
}
static class TestResource implements AutoCloseable {
public void firstMethod() {
System.out.println("firstMethod() 실행 ");
throw new RuntimeException("첫번째 에러 발생");
}
@Override
public void close() throws Exception {
System.out.println("close() 실행 ");
throw new RuntimeException("두번째 에러 발생");
}
}
}
1. 첫번째 메서드에서 에러가 발생했고 close()메서드를 실행된다.
2.만약 finally 에서 에러가 발생한다면 첫번째 메서드의 에러는 두번째 에러에 가려지게 된다.
3.처음 오류가 발생 근원지를 찾을 수 없다.

/Users/dongpillson/Library/Java/JavaVirtualMachines/corretto-17.0.9/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=50215:/Applications/IntelliJ IDEA.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/dongpillson/study/TIL/out/production/TIL exam.TryFinally
firstMethod() 실행
close() 실행
Exception in thread "main" java.lang.RuntimeException: 두번째 에러 발생
at exam.TryFinally$TestResource.close(TryFinally.java:23)
at exam.TryFinally.main(TryFinally.java:9)
Process finished with exit code 1
try-with-resources 적용
package exam;
public class TryWithResources {
public static void main(String[] args) throws Exception {
try (TestResource testResource = new TestResource();) {
testResource.firstMethod();
}
}
static class TestResource implements AutoCloseable {
public void firstMethod() {
System.out.println("firstMethod() 실행 ");
throw new RuntimeException("첫번째 에러 발생");
}
@Override
public void close() throws Exception {
System.out.println("close() 실행 ");
throw new RuntimeException("두번째 에러 발생");
}
}
}
두개의 에러가 발생하는것을 확인할 수 있다.
