oks16
oks16

Reputation: 1294

Java fundamental - a little confusion on return type and return statement in methods

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.

Upvotes: 3

Views: 207

Answers (1)

JB Nizet
JB Nizet

Reputation: 691625

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;
    }
}

Upvotes: 10

Related Questions