Issue
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?
}
Solution
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.
Answered By - kaya3
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.