3

メソッドが Method.invoke メソッドから呼び出されたときに、コードで例外をキャッチできないようです。メソッド自体の内部からどのようにキャッチできますか?

void function() {
  try {
    // code that throws exception
  }
  catch( Exception e ) {
    // it never gets here!! It goes straight to the try catch near the invoke
  }
}

try {
  return method.invoke(callTarget, args);
}
catch( InvocationTargetException e ) {
  // exception thrown in code that throws exception get here!
}

ありがとう!

4

4 に答える 4

5

からスローされた例外を返すメソッドをMethodInvocationExceptionチェックすることで、の本当の原因を取得できます。getCause()function()

getCause():返された例外を再帰的に呼び出して、自分のものに到達する必要がある場合があります。

:をgetCause()返しますThrowable。実際の型 (instanceofまたは などgetClass())を確認する必要があります。

: 「原因」が利用できない場合はgetCause()戻りnullます-スローされた実行の基本的な原因に到達しました

更新

catch()infunction()が実行されない理由は、それが でxxxErrorはないためException、それcatchをキャッチできません-特定のエラーをすべて宣言したくない場合は、いずれかcatch(Throwable)またはcatch(Error)inを宣言します-これは通常、悪い考えであることに注意してください( function()? で何をディオしOutOfMemoryErrorますか。

于 2012-06-15T16:38:50.507 に答える
4

でキャッチできない理由の 1 つは、 のサブクラスではないUnsatisfiedLinkErrorことExceptionです。実際、これは のサブクラスです。UnsatisfiedLinkErrorExceptionError

エラー例外のキャッチには注意が必要です。ほとんどの場合、非常に悪いことが起こったことを示しており、ほとんどの場合、それらから安全に回復することはできません。たとえばUnsatisfiedLinkError、JVM がネイティブ ライブラリを見つけられず、そのライブラリに依存するものは (おそらく) 使用できないことを意味します。一般的に言えば。Error例外は致命的なエラーとして扱われるべきです。

于 2012-06-15T16:44:22.787 に答える
0

通常どおり例外をスローします。インボーク内にあるという事実は違いはありません。

public class B {
    public static void function() {
        try {
            throw new Exception();
        } catch (Exception e) {
            System.err.println("Caught normally");
            e.printStackTrace();
        }
    }

    public static void main(String... args) throws NoSuchMethodException, IllegalAccessException {
        Method method = B.class.getMethod("function");
        Object callTarget = null;
        try {
            method.invoke(callTarget, args);
        } catch (InvocationTargetException e) {
            // should never get called.
            throw new AssertionError(e);
        }
    }
}

版画

Caught normally
java.lang.Exception
at B.function(B.java:15)
... deleted ...
at B.main(B.java:26)
... deleted ...
于 2012-06-15T16:39:09.903 に答える
0

MethodInvocationExceptionメソッドを間違って呼び出していることを意味します。try ブロック内に到達することさえできません。ドキュメントから:

Signals that the method with the specified signature could not be invoked with the provided arguments.

編集: これが Spring MethodInvokationException の場合、Apache Velocity は関数の例外をラップします。

于 2012-06-15T16:43:54.390 に答える