2 ms·
Here are a bunch of error-handling strategies that I'm aware of (which one is valid depends on the situation). - Die immediately / assume the error won't happe
by jstimpfle 6y ago
Here are a bunch of error-handling strategies that I'm aware of (which one is valid depends on the situation).
- Die immediately / assume the error won't happen, but still code defensively.
- Throw an exception (in languages that support this). setjmp() / longjmp() also falls in this category, although it is hard to do correctly.
- Return an error code to the calling function
- Contain the error in a data structure.
The last is a truly object-oriented approach. In larger systems this is the one that scales. Its advantage is that it decouples the error detection from the handling (temporal decoupling) and allows the error to be handled asynchronously. This is a property that exceptions don't have.
Exceptions are, in my experience, not nice to use. If you actually want to handle errors (i.e. not use them only as a glorified die() function) the code gets really ugly - you tend to use them like error return values, but with more verbose syntax (having two return mechanism is bad since it reduces compatibility of code).
I know a situation where exceptions can be useful: when interpreting a chunk of code in a sandbox in a synchronous fashion - i.e. you call the interpreter function of that virtual process, and that process either completes successfully or terminates with an exception. The virtual process is then cleaned up. There is no possibility to interrupt the interpretation and resume some time later.
This is more of a toy setting, though. You don't write complex systems like that.
- a1369209993 6y ago> If you actually want to handle errors (i.e. not use them only as a glorified die() function) the code gets really ugly And conversely, if you do want a glorified die() function, you want a actual glorified die() function, not something that encourages the caller to 'recover', pick up your undefined, probably-corrupted data structures, and continue trying to use them.