3 ms·
When to use exceptions is very simple. When a function is unable to perform its task, throw an exception. It's that simple. Do not use error codes to tell the
by Codester 14y ago
When to use exceptions is very simple.
When a function is unable to perform its task, throw an exception. It's that simple. Do not use error codes to tell the caller "I cannot do what you asked", throw an exception.
Here are some reasons:
1) Programmers pathologically ignore or forget to check return codes from functions and now there are hard to find bugs in the program
2) A clean and beautiful algorithm is made obscure by messy error handling code
3) Indecision and disagreement about how to deal with errors in a program: throw exceptions
4) Return codes cannot provide enough information about an error in order to decide how to handle it
5) Many functions cannot return error codes (Constructors, operator overloads, conversion operators)
6) Return codes corrupt the meaning of the word "function" and destroy the code's usability as a function
7) The need to signal an error condition in code that has no provision for dealing with errors because when it was written no one expected that an error could occur here
8) Functions tangled with return code checking, propagate their problems to anyone else using them, spreading complexity like a cancer
9) Error handling code doesn't get tested
10) Consistent error handling with return codes triples your code size because every function call will need "if fail then return fail code"
11) Errors are occurring in the program but where to look in tens of thousands of lines of code? Exception constructors can log when, where and how telling you exactly where to look.
- philwelch 14y ago2 is a completely separate concern. It's best to do all your error handling at once, at the beginning of the function, rather than mixing it in with your algorithmic code. But that style has nothing to do with whether you throw exceptions or return error codes; you can return error codes early, and you can throw exceptions in the middle of your algorithmic code. On the other side of things, if you're calling functions you expect to handle errors, wrapping that up in a try/catch block is no less messy than checking the validity of your objects as you receive them from those function calls.
- mikmoila 14y agoDesign by Contract - types of preconditions and exceptions is very powerfull tooling for dealing with situations not expected to happen during coding. I would still to keep error handling and detection as separate issues. E.g merely throwing and exception or letting it to happen is often merely error detection, and handling is still to be done somewhere else. I think that exception systems merits are in keeping the subsystems decoupled by giving clear and systematic signaling channel to be used in error-detection situations.