A method is not always required to return a value; in particular, it is also allowed to exit by throwing an exception (in this case, the value is not returned).
Edit: In particular, the rules for the method body that return int :
- All
return in a method must return an expression convertible to int - The end of the method block cannot be accessed.
In your example, the compiler can prove that M2 always exits by throwing, so the end of the method block is unavailable (satisfies rule No. 2). There are also no return that also satisfy rule # 1. Therefore, this is a valid method definition.
On the other hand, M1 does not satisfy rule # 2, therefore it is not legal.
You are probably mistaken in an error message that does not mention throwing at all, but consider that in almost all cases methods with return values make return instead of throwing - the compiler just says that you probably want to forget to do it.
source share