Why method that calls another one which throws RuntimeException needs return statement?

AdnanM91 :

Why unreachable statement is not identified by javac ?

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

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

The compiler simply isn't designed to analyse your code that deeply.

For directThrow, the compiler looks at it and says, "I see you have a throw statement, so the method will terminate abruptly here, no need for a return statement then!"

For indirectThrow, the compiler looks at it and says, "I only see a method call. Hey programmer! You need a return statement here!"

The compiler doesn't look at what directThrow actually does. I think this is quite reasonable, because the benefit of analysing what every method you call does is really small, compared to the cost of increased compilation time. Think about what the compiler needs to check to make sure that directThrow will always throw an exception. The most important thing being, is it overridden by anything? Can you even check that? Can you even make sure that no class in the future will subclass your class and override that method (give your class and directThrow are both non-final)?

If you have some complicated exception-throwing logic that you want to extract into a method, you can extract it into a method that returns the Exception:

private Exception someComplicatedLogicThatGivesAnException() { ... }

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=308799&siteId=1