In C++11 and later, an exception_ptr
to the the current exception can be retrieved using current_exception()
. Is it possible at runtime to determine the type of the exception being pointed to?
More precisely, how to get the a reference to a type_info
of the exception pointed to by an exception_ptr
? I know it is possible to catch
based on the type, but then the programmer would need to write catch
blocks for all possible the types of exceptions, which is not a solution for this problem.
try {
userProvidedRuntimePlugin.executeAction(); // May throw anything
} catch (...) {
auto e = std::current_exception();
std::type_info & info = /* ??? */;
std::cerr << "Exception of type " << info.name() << " thrown." << std::endl;
}
Try something like the following:
#include <cxxabi.h>
using namespace __cxxabiv1;
std::string util_demangle(std::string to_demangle)
{
int status = 0;
char * buff = __cxxabiv1::__cxa_demangle(to_demangle.c_str(), NULL, NULL, &status);
if (!buff) return to_demangle;
std::string demangled = buff;
std::free(buff);
return demangled;
}
try
{
/* .... */
}
catch(...)
{
std::cout <<"exception type: '" << util_demangle(abi::__cxa_current_exception_type()->name()) << "'\n";
}