问题
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?
回答1:
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.
回答2:
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;
}
}
回答3:
While it is possible to write your code in such a way that an exception AND a value can be derived from a function call (see the above posts), it should NEVER be done in proper coding.
I would love to a see a link to the documentation on this API. API's should place a priority on clarity. Throwing an exception and returning a value leaves the question of whether the value that was returned is safe to use or if it is invalid.
Remember, try/catch blocks are the OTHER method of handling exceptions. They don't pass the exception to the calling method, but handle it internally in a way that the developer deems appropriate.
If, for debugging purposes, you need to see the resulting value in the case of an exception, then Bohemian's idea works well.
来源:https://stackoverflow.com/questions/7219963/return-a-value-and-throw-an-exception