C++ Coding Standards: Report, Handle, and Translate Errors Appropriately
Summary
Know when to say when: Report errors at the point they are detected and identified as errors. Handle or translate each error at the nearest level that can do it correctly.
Discussion
Report an error (e.g., write throw ) wherever a function detects an error that it cannot resolve itself and that makes it impossible for the function to continue execution. (See Item 70)
Handle an error (e.g., write a catch that doesn't rethrow the same or another exception or emit another kind of error code) in the places that have sufficient knowledge to handle the error, including to enforce boundaries defined in the error policy (e.g., on main and thread mainlines; see Item 62) and to absorb errors in the bodies of destructors and deallocation operations.
Translate an error (e.g., write a catch that does rethrow a different exception or emits another kind of error code) in these circumstances:
- To add higher-level semantic meaning: For example, in a word processing application, Document::Open could accept a low-level unexpected-end-of-file error and translate it to a document-invalid-or-corrupt error, adding semantic information.
- To change the error handling mechanism: For example, in a module that uses exceptions internally but whose C API public boundary reports error codes, a boundary API would catch an exception and emit a corresponding error code that fulfills the module's contract and that the caller can understand.
Code should not accept an error if it doesn't have the context to do something useful about that error. If a function isn't going to handle (or translate, or deliberately absorb) an error itself, it should allow or enable the error to propagate up to a caller who can handle it.
Exceptions
It can occasionally be useful to accept and re-emit (e.g., catch and rethrow) the same error in order to add instrumentation, even though the error is not actually being handled.
References
[Stroustrup00] §3.7.2, §14.7, §14.9 • [Sutter00] §8 • [Sutter04] §11 • [Sutter04b]