constrctor
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13

Thread: constrctor

Hybrid View

  1. #1
    Join Date
    Sep 2003
    Posts
    815

    constrctor

    I have a constructor that calls a function that return a value
    if the function fails what can I do can I stop constructing the object?
    How do I notify the client who created the object that there was a failure?

    I mean
    Client side:
    CMyClass myClass;

    and myClass constructor do that:

    MyClass::MyClass
    (
    Init1();
    Init2();
    }

    what if Init1() or Init2() fails??

  2. #2
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128
    If I am not wrong, I think you can throw an exception in your constructor.

  3. #3
    Join Date
    Sep 2003
    Posts
    815
    How will the client creating the class object
    will know about the failure?

  4. #4
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,471
    By catching the exception
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


  5. #5
    Join Date
    Jun 2002
    Location
    Letchworth, UK
    Posts
    1,019
    Throw an exception. The catcher can find out what happened. If you use auto_ptr, it will also free the memory.
    Succinct is verbose for terse

  6. #6
    Join Date
    Sep 2003
    Posts
    815
    can you please show me how what do i do with this try catch at the client side?

    I mean my client side do:

    MyClass myClass; //how do I know here if exception was thrown??


    and MyClass constructor looks like that

    try
    {
    if(Init1() != OK)
    //throw exception here?, what kind
    if(Init2() != OK)
    //throw exception here?, what kind
    }
    catch() //catch what exception
    {

    }

  7. #7
    Join Date
    Sep 2003
    Location
    Forever Gone... For Now...
    Posts
    1,515
    One idea:
    Code:
    CYourClass::CYourClass
    {
        if( !Init() )
        {
    	CWhateverExceptionYouWant TheEx;
            // Set up TheEx
            throw TheEx;
        }
    }
    Code:
    try
    {
        CYourClass Yadda;
        UseYadda( Yadda );
    }
    catch( CWhateverExceptionYouWant& rTheEx )
    {
        // Use rTheEx...
    }

    Code:
    void UseYadda( CYourClass& rYadda )
    {
        // ...
    }
    Personally, I avoid throwing exceptions from constructors whenever possible (usually always). As you can see, it is kind of a pain. If you do decide that your constructor should throw, you should make it very well known that it can throw an exception.

    How many classes do you know of, where the constructor throws an exception?
    Last edited by vicodin451; November 12th, 2003 at 07:55 AM.
    Thought for the day/week/month/year:
    Windows System Error 4006:
    Replication with a nonconfigured partner is not allowed.

  8. #8
    Join Date
    Sep 2003
    Posts
    815
    Originally posted by vicodin451
    One idea:
    Code:
    CYourClass::CYourClass
    {
        if( !Init() )
        {
    	CWhateverExceptionYouWant TheEx;
            // Set up TheEx
            throw TheEx;
        }
    }
    I don't understand this part is this the client?

    Code:
    try
    {
        CYourClass Yadda;
        UseYadda( Yadda );
    }
    catch( CWhateverExceptionYouWant& rTheEx )
    {
        // Use rTheEx...
    }

    Code:
    void UseYadda( CYourClass& rYadda )
    {
        // ...
    }
    Personally, I avoid throwing exceptions from constructors whenever possible (usually always). As you can see, it is kind of a pain. If you do decide that your constructor should throw, you should make it very well known that it can throw an exception.

    How many classes do you know of, where the constructor throws an exception?
    ----------------------------------------------------------------

    I haven't seen, but can you tell me what else can I do if the function I call in my constructor fails, how can I inform my client not to call functions of that class?

  9. #9
    Join Date
    Sep 2003
    Location
    Forever Gone... For Now...
    Posts
    1,515
    Originally posted by avi123
    I haven't seen, but can you tell me what else can I do if the function I call in my constructor fails, how can I inform my client not to call functions of that class?
    Well, what I prefer to do is to require a function such as Initialize() to be called prior to using the object. Initialize can return a BOOL or bool to indicate success/failure, or a DWORD error code, or throw an exception, etc. If Initialize fails, further operations on the object should not be performed.
    Code:
    CYourClass Yadda;
    if( Yadda.Initialize() )
    {
        UseYadda( Yadda );
    }
    else
    {
        // Handle failure to initialize...
    }
    or
    Code:
    CYourClass Yadda;
    try
    {
        Yadda.Initialize();
        UseYadda( Yadda );
    }
    catch( CWhateverExceptionYouWant& rTheEx )
    {
        // Handle exception...
    }
    Thought for the day/week/month/year:
    Windows System Error 4006:
    Replication with a nonconfigured partner is not allowed.

  10. #10
    Join Date
    Sep 2003
    Posts
    815
    thanks

    that's what I did

  11. #11
    Join Date
    Aug 2002
    Posts
    58
    Well, what I prefer to do is to require a function such as Initialize() to be called prior to using the object. Initialize can return a BOOL or bool to indicate success/failure, or a DWORD error code, or throw an exception, etc. If Initialize fails, further operations on the object should not be performed.
    My two cents: I used to do this, but now I generally don't like to do this, because it breaks the RAII idiom that I've grown so fond of. Not only that, but it's almost always unneccesary.

    Secondly, since the user is going to have to be aware of how to use the class _anyway_ because you're forcing them to call Initialize() after they've constructed the object, there's no less work involved in requiring them to read the class/documentation to find out that the constructor throws one or more exceptions.

    In my experience, making the users of the class call an arbitrary function or functions before using the class makes it more likely they'll use it incorrectly.

    Regards,
    Bassman

  12. #12
    Join Date
    Sep 2003
    Location
    Forever Gone... For Now...
    Posts
    1,515
    For those that are interested in a deeper discussion of constructors that throw exceptions (and exceptions in general), Robert Schmidt's "Deep C++", "Handling Exceptions" series of articles discusses throwing from a constructor (and much, much more). Particularly, parts 16 and 14.
    Part 16
    http://msdn.microsoft.com/library/de...ep02172000.asp

    Part 14
    http://msdn.microsoft.com/library/de...ep01202000.asp
    Thought for the day/week/month/year:
    Windows System Error 4006:
    Replication with a nonconfigured partner is not allowed.

  13. #13
    Join Date
    Aug 2002
    Posts
    58
    Like anything else, the use of exceptions is fraught with debate and it's closer to a religious argument than it is to an objective cost-benefit analysis.

    In this article specifically, the arguments the author uses are mostly semantic, such as immediately criticizing the 'Spirit of C++' and then moving on later to argue that an initialization function is better because objects can then return the status, "broken but functional."

    How can an object be 'broken' and still functional? There's only two states an object can be in - functional, or not-functional. (I define functional as to mean the methods of the class will satisfy their pre/post conditions.)

    If it's 'half-working', then that constitutes an error in the design of the object - a single object achieving multiple purposes that should probably have been two objects to begin with, one that is functional, one that is not.

    Also, in my book, throwing an exception from the constructor doesn't say, "This object is broken beyond repair," it says, "This object is not usable in the way you've told me to use it either through the specified parameters or due to some other external factors." Since the author never explicitly defines what 'broken' means, he might even be saying about the same thing.

    Regards,
    Bassman

    (All articles cites are from part 16)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center