예, 최종 블록을 사용하여 catch 블록 없이 try 블록을 가질 수 있습니다.
알다시피, 마지막 블록은 항상 실행되는 System.exit()를 제외하고 try 블록에서 예외가 발생하더라도 항상 실행됩니다.
예시 1
public class TryBlockWithoutCatch { public static void main(String[] args) { try { System.out.println("Try Block"); } finally { System.out.println("Finally Block"); } } }
출력
Try Block Finally Block
메소드에 반환 유형이 있고 try 블록이 일부 값을 반환하더라도 최종 블록은 항상 실행됩니다.
예시 2
public class TryWithFinally { public static int method() { try { System.out.println("Try Block with return type"); return 10; } finally { System.out.println("Finally Block always execute"); } } public static void main(String[] args) { System.out.println(method()); } }
출력
Try Block with return type Finally Block always execute 10