重新引发InvocationTargetException目标异常 [英] Re-throw an InvocationTargetException target exception
问题描述
如何重新引发InvocationTargetException的目标异常.我有一个使用反射的方法来在我的一个类中调用invoke()方法.但是,如果我的代码中引发了Exception,则我不必担心InvocationTargetException,而只需要目标异常.这是一个示例:
How does one re-throw the target exception of an InvocationTargetException. I have a method which uses reflection to call the invoke() method within one of my classes. However, if there is an Exception thrown within my code, I am not concerned about the InvocationTargetException and only want the target exception. Here is an example:
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.也许我处理方法不正确?
The primary problem I am facing is that calling throw e.getCause(); doesn't throw an Exception but rather throws a Throwable. Perhaps I am approaching this incorrectly?
推荐答案
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.
}
}
这篇关于重新引发InvocationTargetException目标异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!