我已经写了一个方法,它在try语句中返回一些值。在catch中,我调用了handleException,它将具有理解异常并重新抛出新异常的转换逻辑。这里handleException总是抛出异常,getXYZ()仍然给出编译时错误,期望返回语句。我没有处理异常,我只是抛出新的异常,所以为什么该方法想要返回语句。为什么一个方法需要catch语句中的返回语句,即使catch语句重新抛出异常
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子句。 [请参阅此处的示例](https://docs.oracle.com/javase/tutorial/essential/exceptions/declaring.html)稍后将帮助您确保尝试捕获这些“异常”对象 – Draken