Errors and Assertions

Assertions vs Exceptions

When should I use assertions vs throwing exceptions? They seem to serve similar purposes.

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved