Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't methods need to return a value after throwing an exception?

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?
}
like image 493
Taha Sami Avatar asked Dec 10 '22 23:12

Taha Sami


1 Answers

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.

like image 121
kaya3 Avatar answered May 13 '23 14:05

kaya3