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?
It's not possible to both throw an exception and return a value from a single function call.
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.
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.
Think of exceptions as a separate return type that gets used only when needed.
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.
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; } }
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