Chris Spicer
Chris Spicer

Reputation: 2194

C++ std::exception between Libraries

When I throw an exception in a library, that exception does not get caught by the caller.

To illustrate, if I have this function in a static library:

#include <exception>

void TestClass::ThrowException()
{
   throw new std::exception();
}

... and then call it from an executable:

TestClass t;
try
{
   t.ThrowException();
}
catch (std::exception e)
{
}
catch (...)
{
}

... it is the second catch that receives the exception, not the first, which I did not expect. I suspect that there is some marshalling between the libraries that I am not aware of, which is causing the exception type to not be recognised.

Is it possible to pass an exception between two binaries so that it is recognised as a 'std::exception' by the caller? As a secondary question, is this a good idea?

I am targeting Windows, working with Visual Studio.

Upvotes: 1

Views: 569

Answers (1)

DanDan
DanDan

Reputation: 10562

throw new std::exception();

You are throwing an exception you have created on the heap, so you need to catch it as a pointer:

catch (std::exception *e)

However don't ever do that (you won't know where to delete your allocated memory). Instead just throw an object on the stack:

throw std::exception();

Last point. Don't catch by value, catch by reference. This is because when you subclass your exceptions later you won't slice them. And if you want to be completely correct catch by const reference:

catch (const std::exception& e)

If you're new to all this recommended reading is Effective C++ and it's sequel by Scott Meyers.

Upvotes: 4

Related Questions