Java의 데이터 타입과 예외
Jim White
Java Developer
Exception을 잡아 대응 코드 작성throws로 예외를 호출자에게 넘길 수 있습니다throws 뒤에 예외 타입을 콤마로 구분해 나열합니다public static void someMethod() throws IndexOutOfBoundsException,
NegativeArraySizeException, NullPointerException {
// method code
}
일반적인 try-catch로 Exception 처리
public static void main(String[] args) {
someMethod();
}
public static void someMethod(){
try {
ArrayList<String> games
= new ArrayList<String>();
games.add("Monopoly");
games.add("Chess");
games.get(3);
} catch (IndexOutOfBoundsException e) {
System.out.println(
"Oops - trying to get non-existent item");
}
}
throws로 Exception 처리
public static void main(String[] args) {
try {
someMethod();
} catch (IndexOutOfBoundsException e) {
System.out.println(
"someMethod tried to get non-existent item");
}
}
public static void someMethod()
throws IndexOutOfBoundsException {
ArrayList<String> games
= new ArrayList<String>();
games.add("Monopoly");
games.add("Chess");
games.get(3);
}

Exception은 "재던지기(rethrow)"할 수 있습니다main에서 재던지면 애플리케이션이 종료됩니다
public class RethrowExample {
public static void main(String[] args) {
try {
method1(0);
} catch (ArithmeticException e) {
System.out.println("Oops - tried a bad quotient");
}
}
public static void method1(int divisor) throws ArithmeticException {
method2(divisor);
}
public static void method2 (int divisor) throws ArithmeticException {
int z = 5/divisor;
System.out.println(z);
}
}
Java의 데이터 타입과 예외