static void method (boolean b) {
try {
System.out.println(1);
if(b) throw new ArithmeticException();
System.out.println(2);
} catch (RuntimeException r) {
System.out.println(3);
return; // 메서드를 빠져나간다. (finally 블럭을 수행한 수에)
} catch (Exception e) {
System.out.println(4);
return;
} finally {
System.out.println(5);
}
System.out.println(6);
}
public static void main(String[] args) {
method(true);
method(false);
} // main
}
[결과]-------------------------
1
3
5
1
2
5
6
-------------------------------
[해설]---------------------
예외가 발생하면 1, 3, 5가 출력
예외가 발생 안하면 1, 2, 5, 6 출력
ArithmeticException 은 RuntimeException 의 자손이므로 RuntimeException 이 정의된
catch 블럭에서 처리된다. 이 블럭에는 return 문이 있으므로 메서드를 종료하고 빠져나가게 된다. 이 때 finally 블럭이 수행된다.
댓글 없음:
댓글 쓰기