This is a contrived example. I have a non-void method and it throws an exception. Why don't I have to return a value afterwards? After all, the method is non-void.
public static Toast makeText(Context context, CharSequence text, int duration) {
throw new RuntimeException("Stub!");
//Must return something from here but there is not, Why?
}
Throwing an exception interrupts the flow of control, exiting from the method immediately. When an exception is thrown, no return value is needed because the code which called the method does not complete normally. For example, in the following code, there is no need for foo
to return a number, because int x = foo();
doesn't succeed, it instead propagates the exception:
int foo() {
throw new RuntimeException();
}
void bar() {
int x = foo();
// This line will not be reached
System.out.println(x);
}
Since the code after int x = foo();
won't be executed anyway, there is no need for x
to receive a return value from foo
, and therefore foo
doesn't need to provide a return value.
In fact, a method cannot both return a value and also throw an exception, since returning a value would mean the method completes normally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With