为什么即使 catch 重新抛出异常,方法也需要在 catch 中返回语句

Dee*_*pak 0 java exception-handling

我写了一个方法,它在 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

此方法的另一个版本编译。

public String getXYZ(String input) {
    try {
        return getFromDAO(input);
    } catch (Exception e) {
        throw e;
    }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*ouf 5

你没有在catch块中抛出任何东西,你正在调用你的句柄函数,这最终会导致一个新的异常被抛出,但实际代码getXYZ是在catch. 如果handleException在某些情况下更改为稍后不抛出异常,那么会getXYZ返回什么?