简体   繁体   中英

C++ catching exception in constructor

How can I protect myself from using object which isn't fully created when using exceptions? Should I catch in constructor ? Or maybe it's bad practice ? If I'll catch in constructor object will be created.

#include <stdio.h>

class A
{
public:
    A()
    {
        try {
            throw "Something bad happened...";
        }
        catch(const char* e) {
            printf("Handled exception: %s\n", s);
        }
        // code continues here so our bad/broken object is created then?
    }
    ~A() 
    { 
        printf("A:~A()"); 
    }

    void Method()
    { // do something
    }
};

void main()
{
    A object; // constructor will throw... and catch, code continues after catch so basically we've got 
              // broken object.

    //And the question here: 
    //
    //* is it possible to check if this object exists without catching it from main? 
    // &object still gives me an address of this broken object so it's created but how can I protect myself 
    // from using this broken object without writing try/catch and using error codes?
    object.Method(); // something really bad. (aborting the program)

};

The language itself has no concept of an object being "invalid" in any detectable way.

If the exception indicates that a valid object can't be created, then it shouldn't be handled within the constructor; either rethrow it, or don't catch it in the first place. Then the program will leave the scope of the object being created, and it won't be possible to incorrectly access it.

If that isn't an option for some reason, then you'll need your own way to mark the object as "invalid"; perhaps set a boolean member variable at the end of the constructor to indicate success. This is flaky and error-prone, so don't do it unless you've got a very good reason.

If the object is in an invalid state when a certain exception is thrown, then I would let the exception unwind the call stack so the caller can be notified (and therefore react) to such things.

However, if the exception is one you can recover from, it may be worth trying to do so depend on your application. Make sure you use something like a logger or even simply stderr to indicate this is happening though.

I am going to suggest a first iteration of doing something more like this:

   try {
        throw "Something bad happened...";
    }
    catch(const std::exception e) {
        cerr << e.what () << endl ; // Better off in the main
        throw ;
    }

Two things here:

  1. Unless your exception handler handles the exception, it should throw.

  2. Always use exception classes based upon std::exception to that you can always find out what the problem was as shown above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM