My understanding is that in Java if a method declare a return type, compilation fails if we don’t put a return statement in the method. But the following code compiles successfully.
public int test() throws Exception{
throw new Exception("exception");
}
Now I am a little confused. I think my understanding is wrong. Can someone please clarify?
Thank you.
A Java method must either return, or throw an exception. The compiler refuses to compile if all the possible code paths don’t lead to either a return or an exception. The unique code path in this method throws an exception, so it’s valid.
What would be invalid would be this, because if
i <= 0, nothing is returned, and no exception is thrown:It would be valid if changed to