Nested Exceptions

Performance Impact of Nested Exceptions

Is there a performance penalty when using nested exceptions compared to regular exceptions?

Abstract art representing computer programming

Using nested exceptions does introduce some overhead compared to regular exceptions:

  1. std::throw_with_nested() dynamically allocates memory to create the nested exception object. This allocation has some time and space overhead.
  2. Unwinding nested exceptions requires additional processing. With regular exceptions, the runtime just needs to find the nearest matching catch block. With nested exceptions, it needs to recursively unwind each level of nesting.

However, in most cases this overhead is negligible and is outweighed by the benefits of more expressive error handling. Exceptions should be used for exceptional circumstances anyway, not in performance-critical paths.

If you do find that exception handling is a bottleneck in your code, you can consider techniques like:

  • Use non-throwing functions where possible in performance-critical code.
  • Catch exceptions by reference to avoid copying.
  • Use noexcept to mark functions that don't throw, allowing the compiler to optimize.

But in general, the performance impact of nested exceptions specifically is not something to worry about prematurely. Use them when they make your error handling clearer and more robust.

This Question is from the Lesson:

Nested Exceptions

Learn about nested exceptions in C++: from basic concepts to advanced handling techniques

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

This Question is from the Lesson:

Nested Exceptions

Learn about nested exceptions in C++: from basic concepts to advanced handling techniques

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