I am looking for a function/code that returns the current exception object. In other words, the exception object that represents the exception currently being handled (by the catch
block).
For example:
try
{
// throws an exception
}
catch (const std::exception& Exc)
{
DoSomething();
}
void DoSomething() {
// How to get the "Exc" here?
}
In other words, I need a C++ equivalent of Delphi's ExceptObject
function.
The code above is just an example. The real code looks more like this:
catch (...)
{
A3rdPartyCode();
}
void A3rdPartyCode() {
MyCode();
}
void MyCode() {
// Does not work, returns NULL:
TObject* = ExceptObject();
// ???
// Need to know the current exception, if present
}
Most likely you are looking for a solution in the wrong way, trying to match Delphi and C++ line for line. Anyway, here's an example of how std::current_exception
can be used:
#include <iostream>
#include <exception>
void f()
{
throw "exception from f()";
}
std::exception_ptr pce;
void g() noexcept
{
try
{
f();
}
catch (...)
{
pce = std::current_exception();
}
}
void h() noexcept
{
try
{
if ( pce )
std::rethrow_exception(pce);
}
catch (const char* e)
{
std::cout << e;
}
}
int main()
{
g();
h();
}
std::current_exception
is useful, for example, if you are processing a collection in a secondary thread using a function that can throw for each item in the collection. Instead of interrupting the processing, you can store the exception and forward it to the main thread later.