@634

メソッドの呼び出し側で例外処理

Advertisement

呼び出し元で例外処理

例外が発生したときに、メソッドの呼び出し元で例外処理を行わせたい場合はキーワードthrowsをつかう。

例:func()メソッド。例外が発生したら、呼び出し元に例外をスローする。
public class Test{
    public static void main(String args[]){
        A a = new A();
		
        try{
            a.func(10);
        }catch(Exception e){
            System.out.println("呼び出し側でキャッチ");
            System.out.println(e);
            System.exit(0);
        }
    }
}

class A{
    private int[] a = new int[10];

                            //throws
    public void func(int n) throws Exception{
        a[n] = 1;
    }
}
結果
呼び出し側でキャッチ
java.lang.ArrayIndexOutOfBoundsException: 10
クラスAのfunc()メソッドで例外が発生。throw指定しているから、そこでは処理せずにメソッド呼び出し元に例外をスローしている。呼び出し元でtry〜catch。

任意の位置で例外をスローする

ユーザが任意の位置で例外をスローさせたいときはthrowキーワードを使う。

例。
public class Test{
    public static void main(String args[]){
        A a = new A();

        try{
            a.func(false);
        }catch(Exception e){
            System.out.println("呼び出し側でキャッチ");
            System.out.println(e);
            System.exit(0);
        }
    }
}

class A{
    private int[] a = new int[10];

    public void func(boolean b) throws Exception{
        if(b){
            System.out.println("なにもなし");
        }else{
            System.out.println("例外を発生させる。");
            Exception ex1 = new Exception();
            //throw
            throw ex1;
        }
    }
}
例外のクラスのオブジェクトを作ってそれをスローさせている。

Advertisement

ショートカット

634
634ブログ
このカテゴリのトップページに戻る
Incubator(Pukiwiki)
634ラボ
   UIコレクションギャラリー
   ZO-3ジェネレーター

サイト検索


Y!ログール