Reputation: 1778
I'm trying to catch an exception that is being thrown from the constructor of an object, which is in the process of being created and passed into the constructor of a std::unique_ptr
.
However, I'm unable to catch the actual exception, and instead have to rely on the ...
operator to catch the exception.
I'm using Microsoft visual C++ 2015.
Am I not able to catch exceptions when they are thrown from a constructor?
Here's my code:
#include <memory>
#include <exception>
#include <iostream>
class Test
{
public:
Test()
{
throw new std::exception("this is a test");
}
};
int main()
{
try
{
auto test = std::unique_ptr<Test>(new Test());
}
catch (const std::exception& e)
{
std::cout << "I am here" << std::endl;
}
catch (...)
{
std::cout << "I am here 2" << std::endl;
}
return 0;
}
The output I see is I am here 2
.
Upvotes: 0
Views: 817
Reputation: 1778
Well, after looking at my own question for a minute I realized I was creating the std::exception
object with the new
operator.
After removing the new
operator, it works as expected.
Upvotes: 1