首页 > 解决方案 > Why method that calls another one which throws RuntimeException needs return statement?

问题描述

Why unreachable statement is not identified by javac ?

public int directThrow(){
     throw new RuntimeException();
    //Compiles fine
}

public int indirectThrow(){
    directThrow();
    // Missing Return Statement error
}

标签: javaexception

解决方案


编译器根本不是为了深入分析您的代码而设计的。

对于directThrow,编译器看着它说:“我看到你有一个 throw 语句,所以方法会在这里突然终止,那么就不需要 return 语句了!”

对于indirectThrow,编译器看着它说:“我只看到一个方法调用。嘿,程序员!你需要一个 return 语句!”

编译器不会查看directThrow实际执行的操作。我认为这是非常合理的,因为与增加编译时间的成本相比,分析你调用的每个方法所做的好处真的很小。想想编译器需要检查什么以确保directThrow总是抛出异常。最重要的是,它是否被任何东西覆盖?你甚至可以检查吗?您甚至可以确保将来没有类将子类化您的类并覆盖该方法(给您的类并且directThrow都是非final)?

如果您想将一些复杂的异常抛出逻辑提取到方法中,则可以将其提取到返回的方法中Exception

private Exception someComplicatedLogicThatGivesAnException() { ... }

public void foo() {
    if (...) {
        throw someComplicatedLogicThatGivesAnException();
    }
}

推荐阅读