문제
다음 Java 코드의 실행 결과를 쓰시오.
Javapublic class Main { static String process() { try { if (Math.random() < 0) { throw new RuntimeException(); } return "SUCCESS"; } catch (RuntimeException e) { System.out.print("CATCH"); return "ERROR"; } finally { System.out.print("DONE"); return "FINAL"; } } public static void main(String[] args) { System.out.print(process()); } }
정답
DONEFINAL
DONEFINAL
해설
Math.random() < 0은 항상 false이므로 예외가 발생하지 않고 try 블록에서 "SUCCESS"를 반환하려 합니다. 하지만 finally 블록이 있으면 먼저 실행되어 "DONE"을 출력하고, finally 블록의 return "FINAL"이 try 블록의 return 값을 덮어씁니다. 따라서 최종적으로 "FINAL"이 반환되어 "DONEFINAL"이 출력됩니다.