10/7 17-6 예외 최종 정리 (Club.ver)
이것도 역시 클래스별로 만들어야함!!
클럽에 사람을 입장시킬건데
옷이 남루하거나 나이가 안되면 입장불가
1.Exception클래스를 상속받아 예외클래스로 만든다.
public class NotGoodAppearanceException extends Exception {
기본생성자
public NotGoodAppearanceException( ) {
super("복장 불량은 입장 불가"); =>Exception의 인자 생성자인 Exception(String message) 호출
}
인자생성자
public NotGoodAppearanceException(String message) {
super(message); => message는 getMessage()로 호출할때 반환되는 예외 메시지
}
}
public class Club {
void entrance(String clothes, int age) throws NotGoodAppearanceException {
if("남루".equals(clothes))
throw new NotGoodAppearanceException(); => 예외
else if("정장".equals(clothes) && age < 20)
throw new NotGoodAppearanceException("나이가 너무 어려요");
else if("정장".equals(clothes) && age > 40)
throw new NotGoodAppearanceException("나이가 너무 많아요");
System.out.println("입장하세요"); => 위에서 다 해당 안되면 그제서야 출력!
}
}
public class ClubApp { 메인에서 실행!!
public static void main(String[ ] args) {
Club club = new Club(); => 메모리생성
try {
club.entrance("남루", 20);
} catch (NotGoodAppearanceException e) {
System.out.println(e.getMessage());
}
try {
club.entrance("정장", 15);
} catch (NotGoodAppearanceException e) {
System.out.println(e.getMessage());
}
try {
club.entrance("정장", 45);
} catch (NotGoodAppearanceException e) {
System.out.println(e.getMessage());
}
try {
club.entrance("정장", 20);
} catch (NotGoodAppearanceException e) {
System.out.println(e.getMessage());
}
}
}
복잡해지면 참 헷깔리...ㅠㅠ