Optional.of(null).orElse();
Obviously the above code will always cause an exception. But what about:
Optional.of(someMethod()).orElse();
with
Object someMethod() { return null; }
You probably think: sure, same thing.
Well, actually that is wrong. What if a subclass overrides someMethod()
to return a value other than null
?! Thus you can't decide at compile time whether that method will always return null at runtime.
Long story short: there are plenty of obvious, and also less obvious situations where the compiler could apply all kinds of techniques, like data flow analysis to determine whether code will result in a runtime exception or not. But there are also many others where that isn't possible.
The point here: it is up to the people defining the language to determine what they expect compilers to care about.
The java people opted for a simple compiler. One that compiles fast, and that isn't overly complicated to implement. Why? Because the compiler simply avoid overly complicated checking.