异常处理C++

Exception-Handling C++

本文关键字:C++ 异常处理      更新时间:2023-10-16

我该怎么做,

我有一个名为LargeInteger的类,它存储最多20位数字。我做了建造师

LargeInteger::LargeInteger(string number){ init(number); }

现在,如果数字是>LargeInteger::MAX_DIGITS(静态常量成员),即20,我不想创建对象并引发异常。

我创建了一个类LargeIntegerException{…};做了这个

void init(string number) throw(LargeIntegerException);
void LargeInteger::init(string number) throw(LargeIntegerException)
{
    if(number.length > MAX_DIGITS)
    throw LargeIntegerException(LargeIntegerException::OUT_OF_BOUNDS);
    else ......
}

所以现在我修改了构造函数

LargeInteger::LargeInteger(string number)
{ try {init(number);} catch(LargeIntegerExceptione) {...} }

现在我有两个问题
1.如果抛出异常,会创建这个类的对象吗
2.如果以上情况属实,该如何处理?

否,如果在构造函数中抛出异常,则不会构造对象(前提是您没有像您那样捕获它)。

所以,不要捕获异常,而是让它传播到调用上下文。

IMO,这是正确的方法——如果对象不能直接初始化,那么在构造函数中抛出异常,不要创建对象。

没有理由在构造函数中捕获异常。你希望构造函数失败,所以构造函数之外的东西必须捕获它。如果构造函数通过异常退出,则不会创建任何对象。

LargeInteger(string num) { init(num); } // this is just fine.