[Java] Chained Exception

누구세요·2024년 9월 4일

Chained Exception(연결된 예외)

  • 체인이라는 이름처럼 예외처리 안에서 또 다른 예외를 발생시키는 것이다.

Main Class

public class Main {
   public static void main(String[] args) {
       try{
           Login login =new Login();
           login.Login();
       }
       catch(Exception e){
           e.printStackTrace();
       }
   }
}

Login Class

public class Login {

   private boolean checkId = false;
   private boolean checkPw = false;

   public void Login() throws Exception {
       try {
           InputCheck();
       }
       catch (Exception e) {
           Exception ex = new Exception("로그인 오류: 로그인에 실패하였습니다.");
           ex.initCause(e); // 로그인 오류 1을 원인으로 등록
           throw ex; // 다시 예외를 던진다.
       }
   }

   public void InputCheck() throws Exception {
       if(!checkId)
           throw new Exception("로그인 오류 1: 존재하지 않는 아이디");
       if(!checkPw)
           throw new Exception("로그인 오류 2: 비밀번호 오류");
   }
}

실행하면 다음과 같은 결과가 나온다.

0개의 댓글