Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

exception

Why unreachable statement is not identified by javac ?

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

public int indirectThrow(){
    directThrow();
    // Missing Return Statement error
}
like image 893
AdnanM91 Avatar asked Apr 22 '26 07:04

AdnanM91


1 Answers

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();
    }
}
like image 119
Sweeper Avatar answered Apr 24 '26 20:04

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!