Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to get handle to exception thrown in generic catch handler

Tags:

c++

Is there any way to get handle to exception thrown inside generic catch block.

try
{
    throw ;
}
catch(...)
{
// how to get handle to exception thrown
}

Thanks

like image 457
noname Avatar asked Dec 28 '25 05:12

noname


1 Answers

You can use std::current_exception.

Rearranging from cppreference:

#include <string>
#include <exception>
#include <stdexcept>

int main()
{
     eptr;
    try {
        std::string().at(1); // this generates an std::out_of_range
    } catch(...) {
        std::exception_ptr eptr = std::current_exception(); // capture
    }
} 

Inside the catch(...) block, the current exception has been captured by the exception_ptr eptr. The exception object referenced by an std::exception_ptr remains valid as long as there remains at least one std::exception_ptr that is referencing it: std::exception_ptr is a shared-ownership smart pointer.

like image 70
Paolo M Avatar answered Dec 30 '25 18:12

Paolo M