Exception 발생시키기

강제로 오류를 발생시키는 throw

throw는 오류를 떠넘기는 throws와 보통 같이 사용됩니다.

public class ExceptionExam3 {   
    public static void main(String[] args) {
        int i = 10;
        int j = 0;
        int k = divide(i, j);
        System.out.println(k);

    }       
    public static int divide(int i, int j){
        int k = i / j;
        return k;
    }   
}

위의 코드를 에러가 발생하지 않게 수정

public class ExceptionExam3 {
    public static void main(String[] args) {
        int i = 10;
        int j = 0;
        int k = divide(i, j);
        System.out.println(k);      
    }

    public static int divide(int i, int j){
        if(j == 0){
            System.out.println("2번째 매개변수는 0이면 안됩니다.");
            return 0;
        }
        int k = i / j;
        return k;
    }
}

에러도 발생하지 않고, 올바르지 않은 결과를 리턴하지 않도록 수정

public class ExceptionExam3 {
    public static void main(String[] args) {
        int i = 10;
        int j = 0;
        int k = divide(i, j);
        System.out.println(k);

    }       
    public static int divide(int i, int j) throws IllegalArgumentException{
        if(j == 0){
            throw new IllegalArgumentException("0으로 나눌 수 없어요.");
        }
        int k = i / j;
        return k;
    }   
}