Thread: help, throwing exception from constructor

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    113

    help, throwing exception from constructor

    hi I'm learning c++ from a book, know im on exception handling, but the book do not explain how to deal with exceptions when an error happens while creating an object, how i deal with this? heres my idea but dont works
    Code:
    class Car{
             public:
                  Car(int speed){
                         cout << "constructor called";
                         if(speed > 500)
                           throw speed; 
                 }
                 
                //I need to catch the exception and call the destructor
                //any idea?
                catch(int spd){
                    cout << "at " << spd " you'r travelinig too fast";
                } 
                ~Car(){
                         cout << "Destructor called";
                 }
    };
    
    int main{
        Car toyota(1500);
       //error because 1500 is too fast, so destructor must be called     
       //here, or in other words object must be destroyed.
        ....
       //code continues with object toyota already destroyed
       
       return 0;
    }
    //im attaking this problem fine or not? how i do it?
    //the books says !when u throw an exception from a constructor..
    //the destructor is called" but this is not working to me"

    thanks for any help , and please excuse my poor english

  2. #2
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    I don't believe it does. At any rate, when I have something in a constructor that may fail, I usually put it into a separate initialization function, and then make a static builder. Ex:
    Code:
    class Car
    {
    public:
       static Car* buildCar(int speed)
       {
          Car* car = new Car( );
          bool success = car->init( );
          if (!success)
          {
             delete car;
             car = 0; // Set pointer to NULL.
          }
          return car;
       }
    
       ~Car( ) { }
    private:
       Car( ) { }
    
       bool init(int sp)
       {
          if(sp > 500)
             return false;
          speed = sp;
          return true;
       }
    
       int speed;
    };

  3. #3
    Registered User
    Join Date
    Mar 2004
    Posts
    113
    good zach, thanks a lot for the code

  4. #4
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572

    Know about constructor failures

    You seem to be misunderstanding slightly. Lets follow the flow of execution of your code. You TRY to construct a car object. So we follow like a debugger into the constructor. We hit a decision that causes an exception to be thrown. This passes control to the catch block and a nice message is printed. Now why didnt the destructor get called you are asking yourself. Well it doesnty need to be thats why. Your object never existed and as it never existed it cannot be destroyed. Your Car object would only come into existance and be in a valid state for destruction if you had reached the end of the constructor block but that never happened in this case due to an exception being thrown. Change your code to make two Car objects, one legal and one illegal and you will see only one destructor get called. Objects never exist unless the end of the constructor is reached.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  5. #5
    Registered User
    Join Date
    Mar 2004
    Posts
    113
    whoa thats why :-)

    thanks stoned
    so all the variables i created whit the "new" in the constructor will be cleaned from memory too?

  6. #6
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    If by that you mean do subobjects of partially constructed objects get cleaned up then if they are fully constructed (i.e. their constructors finished without emitting exceptions) then their destructors will be called. Knock up a small example and have a play. It is the finest way to learn what happens. Anything you dont understand well thats what this forum is for. Play with some code. Investigate which destructors get called and try to work out why and in what order.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Exception handling in a large project
    By EVOEx in forum C++ Programming
    Replies: 7
    Last Post: 01-25-2009, 07:33 AM
  2. exception handling
    By coletek in forum C++ Programming
    Replies: 2
    Last Post: 01-12-2009, 05:28 PM
  3. CRecordset::Open() is throwing an exception
    By cpjust in forum Windows Programming
    Replies: 1
    Last Post: 02-13-2008, 12:15 PM
  4. Signal and exception handling
    By nts in forum C++ Programming
    Replies: 23
    Last Post: 11-15-2007, 02:36 PM
  5. Deconstructor throwing exception
    By subdene in forum C++ Programming
    Replies: 13
    Last Post: 06-26-2004, 03:52 AM