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.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Using Assert in Release Builds
The lesson mentions that assert() calls are sometimes stripped out in release builds for performance. What if I want to keep some critical assertions enabled in release builds?
Using static_assert with Non-constexpr Expressions
Can static_assert() be used with expressions that are not known at compile-time, such as values read from a file or user input?
Avoiding Side Effects in Assertions
Is it okay to use assert() with expressions that have side effects, like assert(++x > 0)? Or should assertions be side-effect free?
Defensive Programming with Assertions
How can I use assertions to practice "defensive programming" and make my code more robust?
Using static_assert in Template Code
The lesson shows an example of using static_assert() with std::is_floating_point to validate template parameters. What are some other common type traits I can use for template validation?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant