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:
public int test() throws Exception {
int i = new Random().nextInt();
if (i > 0) {
throw new Exception("exception");
}
}
It would be valid if changed to
public int test() throws Exception {
int i = new Random().nextInt();
if (i > 0) {
throw new Exception("exception");
}
else {
return 0;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.