본문 바로가기

알고리즘/문제 풀이

예외 처리 _Quiz_11

public class _Quiz_11 {
    public static void main(String[] args) {

        int errorCode = 0;


        try{
            if(errorCode ==0) {
                System.out.println("상품 구매를 완료하였습니다.");
            }
            else if(errorCode == 1) {
                throw new timeOutException("상품 구매 가능 시간이 아닙니다.");
            }

            else if (errorCode == 2) {
                throw new soldOutException("해당 상품은 매진되었습니다.");
            }

            }catch (timeOutException e){
                System.out.println(e.getMessage());
                System.out.println("상품 구매는 20시 부터 가능합니다.");
            }catch (soldOutException e){
                System.out.println(e.getMessage());
                System.out.println("다음 기회에 이용해주세요.");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println("모든 예외를 처리합니다.");
        }
    }
}

class soldOutException extends Exception {
    public soldOutException(String message) {
        super(message);
    }
}

class timeOutException extends Exception {
    public timeOutException(String message) {
        super(message);
    }
}

sold out Exception 예외 객체를 생성해서 던질 때, 해당 예외만 전문으로 다루는 catch가 있을 경우 해당 catch가 잡아서 처리함. 

전체를 다루는 Exception e는 어떤 예외를 전문으로 다루는 catch가 없을 때 가동함. (우선순위가 낮다.)

'알고리즘 > 문제 풀이' 카테고리의 다른 글

2058 중간값 더하기  (0) 2023.05.04
SW Expert Academy D1 - 2063 중간값 찾기  (0) 2023.05.02
백준 10818번 최대 최소  (0) 2023.02.28
[JAVA 퀴즈 #10] 나도 코딩  (0) 2023.02.23
JAVA Quiz 09  (0) 2023.02.15