例外の再スローについて。


例外が発生したメソッド内で例外処理をして、その例外処理のcatch節内で


throw e;


の一行を書き、呼び出し元でも例外処理を行なう。


(いったん、catch節にハンドルが移ると、その例外処理、例外発生はクリアされるから。)


再スローによって、例外が発生したメソッド内でできるだけの処理を行い、残作業を呼び出し元メソッドでやってもらうようにすることができる。


・再スローを行なわない場合

【コーディング】

package sample7;

public class TestException7 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("main start.....");
try {
hogeMethod();
} catch (ArithmeticException e) {
// TODO: handle exception
System.out.println("ArithmeticException occurs in Main");
}

System.out.println("main end.....");
}

private static void hogeMethod(){
System.out.println("hogeMethod start.....");
try {
System.out.println("try hogeMethod start.....");
int ikekka = 100/0;
System.out.println("try hogeMethod end.....");
} catch (ArithmeticException e) {
// TODO: handle exception
System.out.println("ArithmeticException occurs in hogeMethod");
}
System.out.println("hogeMethod end.....");
}
}

【実行結果】

main start.....
hogeMethod start.....
try hogeMethod start.....
ArithmeticException occurs in hogeMethod
hogeMethod end.....
main end.....

・再スローを行なった場合

【コーディング】

package sample7;

public class TestException7 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("main start.....");
try {
hogeMethod();
} catch (ArithmeticException e) {
// TODO: handle exception
System.out.println("ArithmeticException occurs in Main");
}

System.out.println("main end.....");
}

private static void hogeMethod(){
System.out.println("hogeMethod start.....");
try {
System.out.println("try hogeMethod start.....");
int ikekka = 100/0;
System.out.println("try hogeMethod end.....");
} catch (ArithmeticException e) {
// TODO: handle exception
System.out.println("ArithmeticException occurs in hogeMethod");
throw e;
}
System.out.println("hogeMethod end.....");
}
}

【実行結果】

main start.....
hogeMethod start.....
try hogeMethod start.....
ArithmeticException occurs in hogeMethod
ArithmeticException occurs in Main
main end.....