Getting the address of an exception object from catch (...) C ++

I have an example try / catch block.

try { ... } catch (...) { ... } 

Is there a way to get the address of an exception object or something from inside a catch (...) block?

+4
source share
4 answers

You can do this in C ++ 11 using std::current_exception() , which returns an exception_ptr object that indicates the exception_ptr is currently being processed or a copy of it. "However, as described in other answers, since you have no idea, which type is actually unlikely to be useful. Note that very few operations are defined for std::exception_ptr and actually dereference it "causes undefined behavior. "

The only interesting thing you can do with it is to save the pointer so that you can later rebuild it in a different context using std::rethrow_exception . This is described in detail in the MSDN article "Transporting Exceptions Between Threads".

+2
source

If you know at least something about type, then yes.

The catch(...) syntax does not give a name to the exception object, but you can reconstruct the object and use a more specific catch clause:

 try { throw 0; } catch(...) { try { throw; } catch(int &i) { std::cout << &i << std::endl; } } 
+2
source

How would you use the address?

You can get most exceptions.

 try { // something } catch (const std::exception& e) { // e will be anything derived from std::exception } catch(...) { // any other error, that you know nothing about // possibly log it as a problem, and throw; // pass it on to someone else that might know how to handle it } 
+1
source

You cannot do this because an abandoned object can be of any possible type, including plain old data such as int or double. It is not possible to infer its actual type.

Even if the language gave you a pointer to an object, you still cannot use anything with it, at least not in a safe type. It will be like emptiness * of unknown data. You can try RTTI, but then you can just as well catch the type that you will test.

Any useful action for an abandoned object involves accepting an assumption about its type, for example, a common base class (for example, std::exception or myapp::object ), which allows you to actually catch this type, creating a common catch(...) not necessary.

Usually the least thing to do when catching an exception is to print a message. This is why it is a good idea to get exceptions from std :: exception, which provides this message through the what () function. This eliminates the need for a catch (...).

+1
source

Source: https://habr.com/ru/post/1341847/


All Articles