8

InvocationTargetExceptionのターゲット例外をどのように再スローしますか。リフレクションを使用して、クラスの1つでinvoke()メソッドを呼び出すメソッドがあります。ただし、コード内で例外がスローされた場合、InvocationTargetExceptionについては気にせず、ターゲット例外のみが必要です。次に例を示します。

public static Object executeViewComponent(String name, Component c,
        HttpServletRequest request) throws Exception {

    try {
        return c.getClass()
                .getMethod(c.getMetaData().getMethod(), HttpServletRequest.class)
                .invoke(c, request);
    } catch (InvocationTargetException e) {
        // throw the target exception here
    }
}

私が直面している主な問題は、throw e.getCause();を呼び出すことです。例外をスローしませんが、スロー可能をスローします。おそらく私はこれに間違ってアプローチしていますか?

4

5 に答える 5

19
catch (InvocationTargetException e) {
    if (e.getCause() instanceof Exception) {
        throw (Exception) e.getCause();
    }
    else {
        // decide what you want to do. The cause is probably an error, or it's null.
    }
}
于 2012-04-18T17:23:07.853 に答える
2

Exception#getCauseを返しますThrowable。をスローしているとコンパイラに認識させたい場合は、Exceptionおそらくそれをキャストする必要があります。

throw (Exception) e.getCause();
于 2012-04-18T17:21:27.780 に答える
1

以下は冗長ですが、リフレクションとキャストは避けたいと思います。Java 7 の multi catch 構文が役立つとは思いません (確かではありません)。

public static Object executeViewComponent(String name, Component c,
        HttpServletRequest request) throw KnownException_1 , KnownException_2 , ... , KnownException_n {

    try {
        return c.getClass()
                .getMethod(c.getMetaData().getMethod(), HttpServletRequest.class)
                .invoke(c, request);
    }
    catch ( InvocationTargetException cause )
    {
          assert cause . getCause ( ) != null : "Null Cause" ;
          try
          {
               throw cause . getCause ( ) ;
          }
          catch ( KnownException_1 c )
          {
                throw c
          }
          catch ( KnownException_2 c )
          {
                throw c
          }
          ...
          catch ( KnownException_n c )
          {
                throw c
          }
          catch ( RuntimeException c )
          {
                throw c ;
          }
          catch ( Error c )
          {
                throw c ;
          }
          catch ( Throwable c )
          {
                assert false : "Unknown Cause" ;
          }
    }
}
于 2012-04-18T18:15:27.677 に答える
0

throw キーワードと、キャッチした対応するオブジェクトを使用して、以前にキャッチした例外を再スローできます。

catch (XXXException e)
{
       throw e;
}
于 2012-04-18T17:20:47.050 に答える
0

明示的に宣言せずに原因を再スローできます。

public static Object executeViewComponent(String name, Component c,
        HttpServletRequest request) throw /* known exceptions */ {

    try {
        return c.getClass()
                .getMethod(c.getMetaData().getMethod(), HttpServletRequest.class)
                .invoke(c, request);
    } catch (InvocationTargetException e) {
        // rethrow any exception.
        Thread.currentThread().stop(e.getCause());
    }
}
于 2012-04-18T17:25:10.510 に答える