2

I was reading some notes on C++ and came across the following question

Q: Can a constructor throws an exception? How to handle the error when the constructor fails?

A:The constructor never throws an error.

Now this answer kind of confused me and just to make sure I went online and read that you could always throw exceptions from a constructor. I just wanted to make sure if this way a typo in the notes and that I may not be missing something important.

4

3 回答 3

4

Of course, it can. Even standard containers (e.g. std::vector) throw std::bad_alloc from constructors. This FAQ is telling the truth.

于 2013-05-17T15:55:36.533 回答
4

The notes are wrong, if they're talking about constructors in general. Ctors can indeed throw normally. Perhaps that was discussing a particular class which guarantees nonthrow construction?

On the other hand, it's strongly encouraged to code so that your destructors never throw. It's legal for them to do so, but throwing an exception during stack unwinding results in immediate program termination (a call to std::terminate).

于 2013-05-17T15:56:13.573 回答
1

You can throw an exception from a constructor, but be careful: if object is not properly constructed, destructor will not be called.

class Foo
{
public:
    Foo(int i)
    {
        throw i;
    }

    ~Foo()
    {
        std::cout << "~Foo()" << std::endl;
    }
};

int main()
{
    try
    {
        Foo f(42);
    }
    catch(...)
    {
        std::cout << "Catched" << std::endl;
    }

    return 0;
}

Output:

Catched

To fix this you should encapsulate one constructor into another:

Foo()
{

}

Foo(int i): Foo()
{
    throw i;
}

Output:

~Foo()
Catched
于 2013-05-17T15:58:56.523 回答