我已經寫了一個方法,它在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