例外をプログラムで作成することも可能。
それがthrowです。
#codeprettify{{ throw object; }}
objectはjava.lang.Throwable型でなければならない。
引数で受けた例外オブジェクトを投げることができます
#codeprettify{{ catch (ExceptionType param){
・
・
・
throw param;
・
・
・
} }}
例
#codeprettify{{ class ThrowDemo{
public static void main(String args[]){
try{
System.out.println("Before a");
a();
System.out.println("After a");
}catch(ArithmeticException e){
System.out.println("main:"+e);
}finally{
System.out.println("main:finally");
}
}
public static void a(){
try{
System.out.println("Before b");
b();
System.out.println("After a");
}catch(ArithmeticException e){
System.out.println("a:"+e);
}finally{
System.out.println("a:finally");
}
}
public static void b(){
try{
System.out.println("Before c");
c();
System.out.println("After c");
}catch (ArithmeticException e){
System.out.println("b:"+e);
}finally{
System.out.println("b:finally");
}
}
public static void c(){
try{
System.out.println("Before d");
d();
System.out.println("After d");
}catch (ArithmeticException e){
System.out.println("c:"+e);
<u>throw e;</u> //eで受け取った例外オブジェクトを投げる
//b()のcatchで例外として引っかかる
}finally{
System.out.println("c:finally");
}
}
public static void d(){
try{
int i=1;
int j=0;
System.out.println("Before division");
System.out.println(i/j);
System.out.println("After divisipn");
}catch(ArithmeticException e){
System.out.println("d:"+e);
<u>throw e;</u> //eで受け取った例外オブジェクトを投げる
//c()のcatchで例外として引っかかる
}finally{
System.out.println("d:finally");
}
}
} }}
結果
Before a Before b Before c Before d Before division d: java.lang.ArithmeticException: / by zero d: finally c: java.lang.ArithmeticException: / by zero c: finally b: java.lang.ArithmeticException: / by zero b: finally After d a: finally After a main: finally
また、新しい例外オブジェクトを作成して投げるには
#codeprettify{{ throw new ExceptionType(args); }}
ExceptionTypeは例外オブジェクトの型で、argsはコンストラクタの引数リスト(省略可能)です。
処理がthrowに進むとcatchに進みます。
例
#codeprettify{{ class ThrowDemo2{
public static void main(String args[]){
try{
System.out.println("Before a");
a();
System.out.println("After a");
}catch(Exception e){
System.out.println("main:" + e);
}finally{
System.out.println("main: finally");
}
}
public static void a(){
try{
System.out.println("Before throw statement");
<u>throw new ArithmeticException();</u> //例外を意図的に新たに作る
}catch (Exception e){
System.out.println("a:"+e);
}finally{
System.out.println("a: finally");
}
}
} }}
結果
Before a Before throw statement a: java.lang.ArithmeticExcection a: finally After a main: finally