자바 Day 13

Hyunsu·2023년 4월 4일
0

Today I Learned

목록 보기
13/37
post-thumbnail

📝 목차

Chapter 11 예외 처리


Chapter 11 예외 처리

Throwable

예외와 에러로 나뉜다.

📌 Exception : 컴파일러가 예외 처리 코드 여부를 검사

  • ClassNotFoundException
  • InterruptedException 등

📌 Runtime Exception : 컴파일러가 예외 처리 코드 여부를 검사하지 않음

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • NumberFormatException 등

예외 처리 코드

try {
	예외 발생 가능 코드
} catch (에외클래스 e) {
	예외 처리
} finally {
	항상 실행
}

throw 와 throws

  • throw : 예외 발생 시키기
  • throws : 메서드를 호출한 곳으로 책임 전가

사용자 정의 예외

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(message);
	}
}

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 {
		if(!id.equals("blue")) {
			throw new NotExistIDException("아이디가 존재하지 않습니다.");
		}
		
		if(!password.equals("12345")) {
			throw new WrongPasswordException("패스워드가 틀립니다.");
		}
	}
}

Reference

profile
현수의 개발 저장소

0개의 댓글