중첩된 try문 실행 흐름

선종우·2023년 6월 19일
0

1. 중첩된 try문에서 error가 발생하면 어떻게 실행될까

  • 예제 코드
class Main {


    public static void main(String[] args) {

        try{
            System.out.println("out try");
            try {
                System.out.println("in try");
                function();
            } catch (Exception e) {
                System.out.println("in Exception !!");
            }
            System.out.println("try finish");
        }catch(Exception e){
            System.out.println("out exception");
        }

    }

    private static void function(){
        throw new RuntimeException();
    }
}

2. 결과

out try
in try
in Exception !!
try finish
  • try ~ catch는 에러를 정상 흐름으로 바꿔 준다.
  • 따라서 내부 try문은 catch에 의해 처리되고 정상흐름으로 바뀌므로 out exception이 출력된다.

0개의 댓글