Friday, September 12, 2008

c++: exception in constructor

I wonder why people want to make all the stuff in constructor.

Constructor do not return anything, so it can't indicate that it failed to do something.

The only way is (please close your eyes here)to throw an exception(now you can open the eyes).

When you throw an exception in the constructor the destructor will not be called. Because compiler doesn't actually know whether the object had been constructed or not. So it's more safe to omit execution of destructor in this case.

So you should clean the stuff just before throwing the exception:

class A
{
    public:
        A()
        {
            do_stuff();

            if (smth_goes_wrong)
            {
                clean_the_shoes();

                throw ticket_to_hell;
            }  

            do_other_stuff();
        }  
}
Knowing that you can keep safe your code even anything else may throw an exception in your constructor:
class A
{
    public:
        A()
        {
            try
            {
                do_stuff();
            }
            catch (...)
            {
                clean_the_shoes();

                throw;
            }   

            do_other_stuff();
        }   
};
Or even better not to throw the caught exception upstairs and do not call anything that might throw an exception at all. Much better to have an init method that may fail safely and call it after the constructor had been called and you are able to safely handle any exceptions.

No comments: