Error Handling
Explore effective error handling strategies in C++ that distinguish programming errors from runtime errors. Understand how using asserts helps detect bugs during testing and learn when to apply exceptions for recoverable runtime errors. This lesson guides you to optimize error management for better code reliability and performance.
Effective error handling techniques
The first thing to do when designing APIs with proper error handling is to distinguish between programming errors and runtime errors. So, before we dive into error handling strategies, we will use Design by Contract to define what type of error we are dealing with.
Programming error or runtime error?
If we find a violation of a contract, we have also found an error in our program. For example, if we can detect that someone is calling pop_back() on an empty vector, we know that there is at least one bug in our source code that needs to be fixed. Whenever a precondition is not met, we know we are dealing with a programming error.
On the other hand, if we have a function that loads some record from the disk and cannot return the record because of a read error on the disk, then we have detected a runtime error:
The precondition is fulfilled, but the postcondition cannot be met because of something outside of our ...