gpt4 book ai didi

java - 重新抛出 InvocationTargetException 目标异常

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:32:46 26 4
gpt4 key购买 nike

如何重新抛出 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();不会抛出 Exception 而是抛出 Throwable。也许我处理这个问题不正确?

最佳答案

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.
}
}

关于java - 重新抛出 InvocationTargetException 目标异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10214525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com