Return a value AND throw an exception?
I'm working with an API that claims to return true if it succeeds, and false if i开发者_JAVA技巧t 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.
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;
}
}
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.
Although this question is old, I found a library that does so. It is to note that this uncommon and might be misleading to add values to the error object. This library wraps that behavior under the hood so you don't need to do it yourself and cause confusion for others working on your code: https://github.com/bacloud23/eager_return_js
It is in JavaScript but the same implementation can be done in Java.
精彩评论