Throwing Non-Exceptions with std::throw_with_nested()

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

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
}

Nested Exceptions

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

Questions & Answers

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

Handling Nested Exceptions with Multiple Catch Blocks
Can I handle nested exceptions using multiple catch blocks? If so, in what order are they caught?
Performance Impact of Nested Exceptions
Is there a performance penalty when using nested exceptions compared to regular exceptions?
Propagating Nested Exceptions Across Threads
Can I throw a nested exception from one thread and catch it in another thread?
Throwing Nested Exceptions from Destructors
Is it safe to throw nested exceptions from a destructor?
Propagating Nested Exceptions Across DLL Boundaries
Can I throw a nested exception from a function in a DLL and catch it in the calling code?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant