入門書にも書いてある内容ですが、COBOLやC言語にはない挙動なので備忘のためにまとめます。
【パターン1:catch文で例外を受け取る】
①で例外が発生すると、catchに遷移する。
public static void main(String args) {
try{
①
}
catch(Exception e){
…例外処理…
}
}
【パターン2:throwsで呼び出し元に例外を投げる】
computeメソッドではthrowsで呼び出し元に例外を戻す宣言がされている。
computeメソッド内で例外が発生した場合、throwで呼び出し元のmainメソッドに例外を返す。
mainメソッドではその例外をcatchし、例外処理へ遷移する。
public static void main(String args) {
try{
…
compute(x,y);
…
}
catch(Exception e){
…例外処理…
}
}
public int compute(int x,int y) throws IllegalArgumentException {
…
throw new IllegalArgumentException("不正な計算です");
…
}
【例外を受け取らない場合】
computeメソッドでmainメソッドに例外を返しても、mainメソッドには例外を処理する記述がされていない。
この場合、エラーメッセージ「Exception in thread "main" java.lang.IllegalArgumentException: 不正な計算です」とスタックトレースを出力して処理が途中で止まる(異常終了する)。
public static void main(String[] args) {
…
compute(x,y);
…
}
public int compute(int x,int y) throws IllegalArgumentException {
…
throw new IllegalArgumentException("不正な計算です");
…
}