【发布时间】:2016-06-10 20:42:01
【问题描述】:
我写了一个方法,它在 try 语句中返回一些值。在 catch 内部,我调用了 handleException,它将具有理解异常并重新抛出新异常的转换逻辑。这里的handleException 总是抛出异常,getXYZ() 仍然给出编译时错误,期望返回语句。我没有处理异常,我只是抛出新的异常,那么为什么该方法需要返回语句。
public String getXYZ(String input) {
try {
return getFromDAO(input);
} catch (Exception e) {
handleException(e);
}
}
private void handleException(Exception e) {
try {
throw e;
} catch(SomeException se) {
throw new MyRuntimeException("MyException message", se);
} catch(SomeOtherException soe) {
throw new MyRuntimeException("MyException message", soe);
}
}
此方法的其他版本编译。
public String getXYZ(String input) {
try {
return getFromDAO(input);
} catch (Exception e) {
throw e;
}
}
【问题讨论】:
-
另外,您可能希望在方法参数中添加一些 throws 子句。 See here for an example 稍后它将帮助您确保您尝试捕获这些
Exception对象