LoginSignup
0
0

More than 1 year has passed since last update.

JavaのExceptionの中に特定のExceptionが含まれるか再帰的に調べるプログラミング

Last updated at Posted at 2021-06-07

javaの例外(Exception)の中に特定の例外(Exception)が含まれているか、再帰的に調べるコードです。

containsExceptionメソッドの第一引数に特定の例外の型、第二引数に例外(Exception)を指定して呼び出し、特定の例外が含まれている場合trueを返し、含まれていない場合falseを返します。

第二引数がnullの場合、falseを返します。
第二引数がnullではなく、型が第一引数と同じ型の場合、trueを返します。
上記以外の場合、例外の中の例外(cause.getCause())を引数に自分自信を呼び出します。(再帰呼び出し)

Utility.java
package test;

public class Utility {

    public static boolean containsException(Class<?> clazz, Throwable cause) {
        if (cause == null) {
            // 例外(cause)がnullの場合、falseを返す
            return false;
        } else if (clazz.isInstance(cause)) {
            // 例外(cause)の型が引数のclazzの場合、trueを返す
            return true;
        } else {
            // 上記以外の場合、例外(cause)の中に含まれる例外(cause.getCause())を引数に自分自身を呼び出す
            return containsException(clazz, cause.getCause());
        }
    }
}

 
 
以下は上記のcontainsExceptionメソッドを呼び出すMain関数の例です。

e3(Exception)は、e3(Exception)中にe2(IOException)が入っており、e2(IOException)の中にe1(SQLException)が入っている例外です。
第一引数のSQLException.class、第二引数にe3を指定して、containsExceptionメソッドを呼び出して、e3の中にSQLExceptionが含まれるか調べます。
含まれる場合true、含まれない場合falseが表示されます。

Main.java
package test;

import java.io.IOException;
import java.sql.SQLException;

public class Main {

    public static void main(String[] args) {

        Exception e1 = new SQLException("message e1");
        Exception e2 = new IOException("message e2", e1);
        Exception e3 = new Exception("message e3", e2);

        boolean result = Utility.containsException(SQLException.class, e3);

        System.out.println("result=" + result);
    }

}
結果
result=true


以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0