チェック例外が発生した場合、例外処理を行なわないとコンパイルエラーが発生する。


チェック例外の例外処理方法は、以下の二つ。


1,例外が発生したメソッド内でtry-catch節を用いて適切なキャッチをする。

2,例外が発生したメソッド内では例外処理をせず、throwsで例外が発生したという情報を呼び出し元のメソッドに投げ、呼び出し元のメソッドで例外処理を行なう。


20061206 追記

サンプルプログラムでより上記の記述の理解を深める。


下のプログラムだと


if(true) throw new TestException();


の行でコンパイルエラーが出る。


コンパイルエラーをなくすには、上記の1,2に書いてあるように、例外が発生したメソッド内で対処してあげなければいけない。


package exception;

public class TestException extends Exception{
//チェック例外
}


package sample6;

import exception.TestException;

public class TestSample6 {

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

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

private static void throwTestException(){
System.out.println("throwTestException() start.....");
if(true) throw new TestException();
System.out.println("throwTestException() end.....");
}

}