Class destructor and throw

This is a discussion on Class destructor and throw within the C++ Programming forums, part of the General Programming Boards category; I have a small snippet of code I am using for a test purpose. Code: try { CSomeClass Test; // ...

  1. #1
    Unregisterred
    Guest

    Class destructor and throw

    I have a small snippet of code I am using for a test purpose.

    Code:
    try
    {
    
        CSomeClass Test;
    
        // output some stuff here
    
        throw "error";
    
        return 1;
    
    }
    catch(char * error)
    {
    
        // explain error
    
    }
    
    return 0;
    While running some tests I noticed that my class's destructor is being called before the //output some stuff here is even being executed and is NOT being called at the end of the application, is this normal in a try/catch situation?

  2. #2
    pronounced 'fib' FillYourBrain's Avatar
    Join Date
    Aug 2002
    Posts
    2,297
    before the output some stuff here? I can imagine it happening before the catch because it's out of scope but not before the output some stuff here
    "You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Are you sure you didn't mix up the Constructor and the Destructor .
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  4. #4
    moi
    moi is offline
    Registered User moi's Avatar
    Join Date
    Jul 2002
    Posts
    946
    i assume you're printing informative messages to stdout and or stderr, are you remembering to flush them both?
    hello, internet!

  5. #5
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    any objects local to the function will have their destructors called as soon as the throw statement executes.This is normal behaviour for a throw. The c++ standard garantees that local objects get their destructor called in event of an exception.
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21