「Java」throwで例外をスローするサンプル
書式
throw 例外インスタンス
スローした例外はcatchで捕まえます
使用例
package info;
class TestInfo {
static void funA() {
try {
int xx = 62 / 0;
// ArithmeticExceptionの例外をキャッチ
} catch (ArithmeticException e) {
System.out.println("エラーメッセージ11");
// throw eで例外のインスタンスをスローする
throw e;
}
}
}
public class ThrowDemo {
public static void main(String[] args) {
try {
TestInfo.funA();
// 例外をキャッチ
} catch (ArithmeticException e) {
System.out.println("エラーメッセージ22");
}
System.out.println("プログラムが終了です");
}
}
package info;
class TestInfo {
static void funA() {
try {
int xx = 62 / 0;
// ArithmeticExceptionの例外をキャッチ
} catch (ArithmeticException e) {
System.out.println("エラーメッセージ11");
// throw eで例外のインスタンスをスローする
throw e;
}
}
}
public class ThrowDemo {
public static void main(String[] args) {
try {
TestInfo.funA();
// 例外をキャッチ
} catch (ArithmeticException e) {
System.out.println("エラーメッセージ22");
}
System.out.println("プログラムが終了です");
}
}
package info; class TestInfo { static void funA() { try { int xx = 62 / 0; // ArithmeticExceptionの例外をキャッチ } catch (ArithmeticException e) { System.out.println("エラーメッセージ11"); // throw eで例外のインスタンスをスローする throw e; } } } public class ThrowDemo { public static void main(String[] args) { try { TestInfo.funA(); // 例外をキャッチ } catch (ArithmeticException e) { System.out.println("エラーメッセージ22"); } System.out.println("プログラムが終了です"); } }
実行結果
エラーメッセージ11
エラーメッセージ22
プログラムが終了です