본문 바로가기

WIL(What I Learned)

예외, 에러처리 quiz

class ArrayCalculation {

    int[] arr = {0, 1, 2, 3, 4};

    public int divide(int denominatorIndex, int numeratorIndex) throws ArithmeticException, ArrayIndexOutOfBoundsException {
        return arr[denominatorIndex] / arr[numeratorIndex];
    }
}

public class Main {
    public static void main(String[] args) {
        ArrayCalculation arrayCalculation = new ArrayCalculation();

        System.out.println("2 / 1 = " + arrayCalculation.divide(2, 1));
        try {
            System.out.println("1 / 0 = " + arrayCalculation.divide(1, 0)); // java.lang.ArithmeticException: "/ by zero"
        } catch (ArithmeticException arithmeticException) {
            System.out.println("잘못된 계산입니다. " + arithmeticException.getMessage());
        }
        try {
            System.out.println("Try to divide using out of index element = "
                    + arrayCalculation.divide(5, 0)); // java.lang.ArrayIndexOutOfBoundsException: 5
        } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) {
            System.out.println("잘못된 index 범위로 나누었습니다. 타당한 index 범위는 0부터 " + (arrayCalculation.arr.length - 1) + "까지입니다.");
        }


    }

}

스파르타코딩클럽 자바 문법 뽀개기 강의의 예외, 예외처리 단원 quiz 코드이다. 강의 자료 참조하며 풀이 시도하다가 해설 강의를 들었다.

1. method에 throws문을 코딩하였다.

2. 제시된 세 계산식인 2/1, 1/0, 5/0이 왜 에러인지를 알아야 했다. 첫 식은 문제가 없고, 둘째의 경우 0으로 나누는게, 셋째의 경우 5로 나누는게 문제다. 따라서 sout문을 try 처리하고 catch 에 각각의 에러에 해당하는 코딩을 하고 에러문을 띄워주는 코딩도 해준다. 이때 .length를 활용하기도 한다.

'WIL(What I Learned)' 카테고리의 다른 글

TIL  (0) 2021.07.10
날짜와 시간 다루기 quiz  (0) 2021.07.09
Week I Learned  (0) 2021.07.04
항해99 3주차 WIL  (0) 2021.06.27
알고리즘 집중기 회고  (0) 2021.06.23