Nested Exceptions

Throwing Non-Exceptions with std::throw_with_nested()

What happens if I pass a non-exception type to std::throw_with_nested()?

Abstract art representing computer programming

If you pass a non-exception type to std::throw_with_nested(), the behavior is undefined. The C++ standard requires that the argument to std::throw_with_nested() be derived from std::exception.

For example, this code has undefined behavior:

try {
  std::throw_with_nested(42);
} catch(...) {
// undefined behavior
}

To properly use std::throw_with_nested(), ensure you only pass it exceptions:

try {
  std::throw_with_nested(
    std::runtime_error{"Error"});  
} catch (...) {
  // OK, runtime_error derives from std::exception
}
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:

  • 124 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