TIL 3일차

인자약·2023년 11월 22일

TIL

목록 보기
3/14

1. 다음 코드가 실행되었을 때 출력 결과를 작성해보세요.

String[] strArray = { "10", "2a" };
int value = 0;
for (int i = 0; i <= 2; i++) {
	try {
    	value = Integer.parseInt(strArray[i]);
    } catch(ArrayIndexOutOfBoundsException e) {
    	System.out.println("인덱스를 초과했음");
    } catch(NumberFormatException e) {
    	System.out.println("숫자로 변환할 수 없음");
    } finally {
    	System.out.println(value);
    }
}

👉 출력 결과
10
숫자로 변환할 수 없음 // strArray[1] = 2a이므로 숫자로 변환 불가 & 먼저 catch됨
10 // finally
인덱스를 초과했음 // strArray[2]는 없으므로 인덱스를 초과 & 나중에 catch됨
10 // finally

2. login() 메소드에서 존재하지 않는 ID를 입력하면 NotExistIDException을 발생시키고, 잘못된 패스워드를 입력하면 WrongPasswordException을 발생시키려고 합니다. 다음 LoginExample의 실행 결과를 보고 빈칸에 채워보세요.

public class NotExistIDException extends Exception {
	public NotExistIDException() {
    public NotExistIDException(String message) {
    [빈칸]
    👉 super(message);
    }
}
public class WrongPasswordException extends Exception {
	public WrongPasswordException() {}
    public WrongPasswordException(String message) {
    [빈칸]
    👉 super(mesage);
    }
}    
public class LoginExample {
	public static void main(String[] args) {
    	try {
        	login("white", "12345");
        } catch(Exception e) {
        	System.out.println(e.getMessage());
        }
        
        try {
        	login("blue", "54321");
        } catch(Exception e) {
        	System.out.println(e.getMessage());
        }
     }
     
     public static void login(String id, String password) [빈칸] 👉 throws NotExistIDException, WrongPasswordException {
     //id가 blue가 아니라면 NotExistIDException을 발생시킴
     if(!id.equals("blue")) {
     	[빈칸]
     	👉 throw new NotExistIDException("아이디가 존재하지 않습니다.");
     }
     //password가 12345가 아니라면 WrongPasswordException을 발생시킴
     if(!password.equals("12345")) {
     	[빈칸]
        👉 throw new WrongPasswordException("패스워드가 틀립니다.")
     }
  }
}  
profile
인자약velog

0개의 댓글