我从代码开始。这个调用使用反射的方法
try {
Method method = states.getClass().getDeclaredMethod(
getCurrentStateId() + "_" + request.getEvent());
states.setData(request, dataManager);
method.invoke(states);
} catch (NoSuchMethodException e) {
logger.debug("Method " + getCurrentStateId() + "_" + request.getEvent()
+ " cannot be found - invocation not performed.", e);
} catch (IllegalArgumentException e) {
throw new InternalException("Method invocation with reflection failed.", e);
} catch (IllegalAccessException e) {
throw new InternalException("Method invocation with reflection failed.", e);
} catch (InvocationTargetException e) {
throw new InternalException("Method invocation with reflection failed.", e);
}
并使用以下代码调用该方法,该代码抛出PropertiesDontMatchException
(运行时)。
...
if (totalCredits < minimumCredits || totalCredits > maximumCredits) {
throw new PropertiesDontMatchException("Minimum amount of credits=" + minimumCredits
+ ", maximum amount of credits=" + maximumCredits + ". Your amount of credits=" + totalCredits + ". You have to modify your set of subjects.");
}
...
问题是我的运行时异常被包装到InvocationTargetException
第一个代码片段中并被捕获。这不是我想要的。但是根据文档,这是正确的行为。
所以我想出了这个解决方案
...
} catch (InvocationTargetException e) {
if (e.getCause() instanceof PropertiesDontMatchException) {
throw (PropertiesDontMatchException) e.getCause();
}
throw new InternalException("Method invocation with reflection failed.", e);
}
...
这是传播我的运行时异常的正确方法还是有更好的解决方案?