前回で検査例外と非検査例外の違いを説明しました。
実際に簡単なサンプルを書いてみました。
1.通常の例外(検査例外)
public class A {
void test() throws Exception{
System.out.println("test");
}
public static void main(String[] args) {
A a = new A();
a.test();
}
}
2.非検査例外
public class A {
void test() throws RuntimeException{
System.out.println("test");
}
public static void main(String[] args) {
A a = new A();
a.test();
}
}
赤の部分だけが異なるところです。
実際に実行してみて下さいね。
・
・
・
・
・
実行結果は、
1 ではコンパイルエラーになります。
2 ではコンパイルエラーにならず、testと表示されます。
なんとなく分かってもらえたでしょうか?
では、1をコンパイルするためにはどうすればいいでしょうか?
もちろん、例外処理ですね。
さらにExceptionをthrowしてぶん投げてもいいですし、
try~catchで適切に処理してもOKです。
例えば
1-1.
public class A {
void test() throws Exception{
System.out.println("test");
}
public static void main(String[] args) throws Exception {
A a = new A();
a.test();
}
}
1-2.
public class A {
void test() throws Exception{
System.out.println("test");
}
public static void main(String[] args) {
A a = new A();
try{
a.test();
} catch(Exception e){ }
}
}
などですね^^