mercredi 27 janvier 2016

C++11 throwing exception from constructor when making a unique_ptr

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.

Aucun commentaire:

Enregistrer un commentaire