Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a value AND throw an exception?

I'm working with an API that claims to return true if it succeeds, and false if it fails. But, it also claims to throw different exceptions if it fails. How can it return false and throw an exception?

like image 492
mark Avatar asked Aug 28 '11 09:08

mark


People also ask

Can you throw an exception and return a value?

It's not possible to both throw an exception and return a value from a single function call.

How do you return after throwing an exception?

After throwing an exception, you do not need to return because throw returns for you. Throwing will bubble up the call stack to the next exception handler so returning is not required.

How do you return a value and raise an exception in Python?

You can't "raise" and "return" in the same time, so you have to add a special variable to the return value (e.g: in tuple) in case of error. E.g: I have a function (named "func") which counts something and I need the (partial) result even if an exception happened during the counting.

Can an exception be a return type?

Think of exceptions as a separate return type that gets used only when needed.


2 Answers

It's not possible to both throw an exception and return a value from a single function call.

Perhaps it does something like returning false if there's an error, but throwing an exception if the input is invalid.

edit: PaulPRO posted a (now-deleted) answer pointing out that it is technically possible to cause an exception to be thrown in a different thread, while returning a value in the current one. I thought this was worth noting, even if it's not something you should ever see.

like image 161
Jeremy Avatar answered Sep 28 '22 00:09

Jeremy


You can throw an exception that has a (in this case boolean) value:

public class ValueException extends Exception {     final boolean value;      public ValueException(boolean value, String message) {         super(message);         this.value = value;     }      public boolean getValue() {         return value;        } } 
like image 45
Bohemian Avatar answered Sep 27 '22 23:09

Bohemian