2 ms·
yes. > when you cannot handle the error in the current code block and the function interface does not support returning enough information to the caller to det
by laurowyn 6y ago
yes.
> when you cannot handle the error in the current code block and the function interface does not support returning enough information to the caller to detail what went wrong
Exceptions are, fundamentally, an alternate way to return from a function. That's why the general practice is to avoid using them for control flow - there's enough in the language already to support what you want to do, we don't need to instrument the entire stack when I could return a negative value to indicate the error.
The engineering problem to solve is deciding when to turn a void return into a boolean or enum. Just because there is space in the interface for an error code, doesn't mean it's the right choice. But likewise, just because exceptions are available, doesn't mean every error should be thrown.
- jschwartzi 6y agoIt should ultimately be a matter of readability. If it's more readable for you to use Exceptions, by all means use them. But if you're working in a domain where you have control over the type of the return, then choose a range of return values which contains a representation of all possible results of your function and not just the "everything is working" result to be explicit. You don't have to return only primitive types. You can return data structures too, so you can encode the error as part of a return type and treat it and the rest of the data on the same level. In short, it's a little simplistic to go void->integer or void->boolean. You should really be going void->struct or void->class. That gives you wide latitude in defining the range of your output types.