Thread: problem with exception behavior

  1. #1
    Registered User
    Join Date
    Oct 2005
    Location
    Hyderabad, India
    Posts
    33

    problem with exception behavior

    /*
    the code below prints copy constructor called three times , i can trace 2 times , one at throw in myfunction and one at catch(A e) in main .... can somebody explain the third

    */

    Code:
    #include <iostream>
    #include <exception>
    using namespace std;
    
    class A{
      int a;
    
      public:
        A(){
        }
    
        A(A& gaurav){
          a  = gaurav.a;
          cout<<"copy constructor called \n";
        }
    };
    
    void myfunction() {
      A b;
      cout<<"here 1\n";
      throw b;
    }
    
    int main () {
      try
      {
         myfunction();
      }
      catch (int e)
      {
         cout<<e;
      }
       catch(A e)
      {
         cout<<"here";
      }
      return 0;
    }

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Only prints twice for me.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    It depends on the implementation. With my compiler (VC++ 7.1) it is only called twice. If you catch by reference (which is the preferred method anyway), it is only called once. It has to be called once because there needs to be a copy of the object that isn't destroyed when the stack is unwound.

    If you have a debugger, put a breakpoint in the copy constructor and find out why you get three calls.

  4. #4
    Registered User
    Join Date
    Oct 2005
    Location
    Hyderabad, India
    Posts
    33
    i am using Borland C++ 5.5.1 for Win32

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. exception handling
    By coletek in forum C++ Programming
    Replies: 2
    Last Post: 01-12-2009, 05:28 PM
  2. stack trace in exception
    By George2 in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2008, 03:00 AM
  3. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM
  4. Problem with the exception class in MINGW
    By indigo0086 in forum C++ Programming
    Replies: 6
    Last Post: 01-20-2007, 01:12 PM
  5. Replies: 2
    Last Post: 06-21-2006, 04:23 AM