简体   繁体   中英

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

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

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.

The problem is that is C++, an exception is allowed to be of any type and not only a subclass of std::exception . That's the reason why the common idiom is to use only exception classes derived from std::exception to have a coherent interface.

You can always as suggested by @PaoloM use std::current_exception() . But it has some limitations that make it hard to use, because to be allowed to represent any type of exception it is a std::exception_ptr that only can (ref. in cpluscplus.com ):

  • be default-constructed (acquiring a null-pointer value).
  • be copied, including being copied a null-pointer value (or nullptr).
  • be compared against another exception_ptr object (or nullptr) using either operator== or operator!=, where two null-pointers are always considered equivalent, and two non-null pointers are considered equivalent only if they refer to the same exception object.
  • be contextually convertible to bool, as false if having null-pointer value, and as true otherwise.
  • be swapped, and being destructed.

Performing any other operation on the object (such as dereferencing it), if at all supported by the library implementation, causes undefined behavior.

If you want to be able to to serious things with an exception, you should use dedicated exception handlers:

try
{
    throw ;
}
catch (MyException& a) {
// Ok, it is a know type and I know how to deal with it
}
catch (std::exception& e) {
// it is a subclass of std::exception, I can at least use its what() method
catch(...)
{
// I can get a std::exception_ptr from current_exception, but cannot know what to do with it
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM