Catching exceptions from a constructor means that my instance is out of scope afterward

前端 未结 4 1404
北海茫月
北海茫月 2020-12-11 21:18

I have a class whose constructor may throw an exception. Here’s some code that will catch the exception:

try {
    MyClass instance(3, 4, 5);
}
catch (MyClas         


        
4条回答
  •  [愿得一人]
    2020-12-11 22:00

    You should be doing everything you need to do inside the try block:

    try {
        MyClass instance(3, 4, 5);
    
        // Use instance here
    }
    catch (MyClassException& ex) {
        cerr << "There was an error creating the MyClass." << endl;
        return 1;
    }
    

    After all, it is only within the try block that instance has been successfully created and so can be used.

    I do wonder whether your catch block is really handling the exception. If you can't do anything to resolve the situation, you should be letting it propagate.

提交回复
热议问题