如何重新抛出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。也许我接近这个错误?
答案 0 :(得分:16)
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.
}
}
答案 1 :(得分:2)
Exception#getCause
返回Throwable
。如果您希望编译器认为您正在抛出Exception
,那么您可能需要进行强制转换。
throw (Exception) e.getCause();
答案 2 :(得分:1)
以下是冗长的,但我喜欢避免反思和投射。我不认为(但不确定)Java 7的多捕获语法会很有用。
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" ;
}
}
}
答案 3 :(得分:0)
您可以使用throw关键字和捕获的相应对象重新抛出之前捕获的任何异常:
catch (XXXException e)
{
throw e;
}
答案 4 :(得分:-1)
您可以在不明确声明原因的情况下重新抛出原因。
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());
}
}