4 ms·
Another way to support RAII without throwing exceptions is to somehow make the error case an explicit configuration of the class with well-defined behavior. For
by jschwartzi 7y ago
Another way to support RAII without throwing exceptions is to somehow make the error case an explicit configuration of the class with well-defined behavior. For example, in a "File" class with no filedescriptor you could return a defined "error" from any function calls which would require a filedescriptor. Receiving such a return value or return structure would then signal that the File class is not in a working state.
- laurowyn 7y agoyes. > 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 7y 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.
- Koshkin 7y agoI think that's something called 'the Maybe pattern (a monad)'.