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 は「再スロー」できます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におけるデータ型と例外処理