Assertions vs Exceptions
When should I use assertions vs throwing exceptions? They seem to serve similar purposes.
Assertions and exceptions are both mechanisms for handling errors and unexpected conditions in C++, but they're best used in different scenarios. Here's a comparison:
Assertions
- Check for conditions that should never happen if the program is correct
- Catch programming errors and contract violations
- Are typically disabled in release builds for performance
- Terminate the program immediately when they fail
- Example: Asserting that a pointer parameter is non-null
Exceptions
- Handle anticipated runtime errors and exceptional conditions
- Can be caught and handled by the caller
- Remain enabled in both debug and release builds
- Unwind the stack and transfer control to an exception handler
- Example: Throwing an exception when a file fails to open
Here's how you might use them together:
#include <cassert>
#include <stdexcept>
int Divide(int x, int y) {
assert(y != 0);
if (x == 0) {
throw std::domain_error("Division by zero");
}
return x / y;
}
In this example:
- The assertion checks that
y
is non-zero. If this assertion fails, it indicates a bug in the calling code that should be fixed. - The exception handles the case where
x
is zero. This is an anticipated edge case that callers should be prepared to handle.
Some guidelines
- Use assertions to document and enforce preconditions, postconditions, and invariants
- Throw exceptions for error conditions that callers should be expected to recover from
- Don't use assertions for error checking that needs to remain enabled in production code
- Avoid throwing exceptions from destructors, as this can lead to program termination
Ultimately, the choice between assertions and exceptions depends on your error handling strategy and the nature of the error. Assertions are for unrecoverable programming errors, while exceptions are for predictable runtime conditions.
Errors and Assertions
Learn how we can ensure that our application is in a valid state using compile-time and run-time assertions.