check exceptionとuncheck exception
uncheck exception非検査型の異常は、RuntimeExceptionまたはRuntimeExceptionのサブクラスを継承するすべての異常はuncheck exceptionです。
check exception検査型異常は、検査型異常以外の異常は検査型異常となります。check exceptionはプログラマの処理が必要です。
二つの方法の例は次の通りで、一つのuncheck exceptionとcheck exceptionをそれぞれ表しています。
uncheck exception:
in test 1
java.lang.Illegel Acception:アクセス異常を投げ出す…
at comp.xino.studiy.file.Exception Test.test 1(Exception Test.java:8)
at comp.xino.studiy.file.Exception Test.main(Exception Test.java:18)in test 2
Exception in thread“main”java.lang.IlegalArgMentException:パラメータ異常を投げ出す…aa
at comp.xino.studiy.file.Exception Test.test 2(Exception Test.java:13)
at comp.xino.studiy.file.Exception Test.main(Exception Test.java:22)
上記のコードに注意してください。ステートメント関数の場合、check exceptionはthrows異常が出ますが、uncheck exceptionは必要ありません。呼び出し時、check exceptionはtry{}catch{}で異常を捕獲して処理する必要があります。uncheck exceptionは必要ありません。
上記の違い以外に、他の違いがあります。プログラム実行中にuncheck exceptionに会ったら、プログラムは中止され、その後のコードは実行されません。メール関数の変更は以下の通りです。
in test 2
Exception in thread“main”java.lang.IlegalArgMentException:パラメータ異常を投げ出す…aa
at comp.xino.studiy.file.Exception Test.test 2(Exception Test.java:13)
at comp.xino.studiy.file.Exception Test.main(Exception Test.java:17)
test 1関数はまったく実行されていないことが分かります。
check exception検査型異常は、検査型異常以外の異常は検査型異常となります。check exceptionはプログラマの処理が必要です。
二つの方法の例は次の通りで、一つのuncheck exceptionとcheck exceptionをそれぞれ表しています。
uncheck exception:
public static void test2(String param){
System.out.println("in test2");
throw new IllegalArgumentException(" ..."+param);
}
check exception:
public static void test1() throws IllegalAccessException {
System.out.println("in test1");
throw new IllegalAccessException(" ...");
}
呼び出し時:
public static void main(String args[]){
try {
test1();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
test2("aa");
}
実行結果は以下の通りです。in test 1
java.lang.Illegel Acception:アクセス異常を投げ出す…
at comp.xino.studiy.file.Exception Test.test 1(Exception Test.java:8)
at comp.xino.studiy.file.Exception Test.main(Exception Test.java:18)in test 2
Exception in thread“main”java.lang.IlegalArgMentException:パラメータ異常を投げ出す…aa
at comp.xino.studiy.file.Exception Test.test 2(Exception Test.java:13)
at comp.xino.studiy.file.Exception Test.main(Exception Test.java:22)
上記のコードに注意してください。ステートメント関数の場合、check exceptionはthrows異常が出ますが、uncheck exceptionは必要ありません。呼び出し時、check exceptionはtry{}catch{}で異常を捕獲して処理する必要があります。uncheck exceptionは必要ありません。
上記の違い以外に、他の違いがあります。プログラム実行中にuncheck exceptionに会ったら、プログラムは中止され、その後のコードは実行されません。メール関数の変更は以下の通りです。
public static void main(String args[]){
try {
test1();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
test2("aa");
}
実行結果:in test 2
Exception in thread“main”java.lang.IlegalArgMentException:パラメータ異常を投げ出す…aa
at comp.xino.studiy.file.Exception Test.test 2(Exception Test.java:13)
at comp.xino.studiy.file.Exception Test.main(Exception Test.java:17)
test 1関数はまったく実行されていないことが分かります。