如何在构造函数中处理异常

问题描述 投票:0回答:0

我在捕获构造函数抛出的异常时遇到了问题。我已经很好地从另一个类的构造函数中捕获了异常,但是由于某种原因,当我尝试以相同的方式捕获异常时,这个类导致我的程序提前终止。

我想做的很简单。如果ProductionWorker对象的班次号不是1或2,则抛异常InvalidShift。当我这样做时,它似乎可以很好地处理因通过设置函数导致班次编号无效而引起的异常,如下所示:


void setShift(int s) // Works as expected
    {
        // If the shift is not 1 or 2, then throw an exception
        if (s != 1) {
        throw InvalidShift(s);
        } else {
            shift = s;
        }
    }

但是,当我尝试在我的类的构造函数中做同样的事情时,它反而会提前终止。

// Constructor
// Terminates early due to an unhandled exception
ProductionWorker(string aName, string aNumber, string aDate,
                 int aShift, double aPayRate) :
                 Employee(aName, aNumber, aDate)
{
    if (shift != 1) {
        throw InvalidShift(aShift); // Visual Studio complains of an unhandled exception here
    } else {
         shift = aShift; payRate = aPayRate;
    }
}

我是这样称呼它的:

try {
    cout << "Creating ProductionWorker with a bad shift" << endl;
    ProductionWorker invalid("James Quinn", "4254", "05/27/2003", 20, 19.00);
    displayProductionInfo(invalid);

} catch (ProductionWorker::InvalidShift e) { // Code never reaches this point
    cout << "Error: " << e.getShift() << " is not a valid shift number. "
        << "Enter a shift number of either 1 or 2."
        << endl << endl;
}

这是 InvalidShift 类的代码:

class ProductionWorker : public Employee {
public:
    // Exception class
    class InvalidShift {
    private: 
        int shift;
    public: InvalidShift(int shift) {
        this->shift = shift; 
    }
          int getShift() const {
              return shift;
        }
    };
c++ class exception constructor
© www.soinside.com 2019 - 2024. All rights reserved.