Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading