아래 예제에서는 throw로 다음 사람에게 에러메세지를 넘겨줘야 해당 부분 에러메세지가 출력되고, 그 뒷부분도 실행이 된다.
일단 기록을 위해 적어둔다.
import java.io.IOException;
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 a) {
System.out.println("잘못된계산입니다." + a.getMessage());
}
try {
System.out.println("Try to divide using out of index element = "
+ arrayCalculation.divide(5, 0)); // java.lang.ArrayIndexOutOfBoundsException: 5
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("잘못된 인덱스 범위입니다." + (arrayCalculation.arr.length - 1) + "까지만 가능합니다.");
}
}
}
https://opentutorials.org/module/516/6226
예외 1 - 문법 - Java
성공과 실패 객체 지향 이전까지가 프로그램을 동작하게 하는 법이라면 객체 지향은 웅장한 소프트웨어를 만들기 위한 방법이라고 할 수 있다. 그리고 필자는 이러한 지식을 성공하기 위한 지
opentutorials.org