8

如何重新抛出 InvocationTargetException 的目标异常。我有一个方法,它使用反射在我的一个类中调用 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(); 不会抛出异常,而是抛出 Throwable。也许我不正确地接近这个?

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。如果您希望编译器认为您正在抛出 anException那么您可能需要强制转换它。

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 回答