Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 异常处理C++;_C++_Exception Handling - Fatal编程技术网

C++ 异常处理C++;

C++ 异常处理C++;,c++,exception-handling,C++,Exception Handling,我该怎么做 我有一个名为LargeInteger的类,它存储了许多最大20位数字。 我做了构造器 LargeInteger::LargeInteger(string number){ init(number); } LargeInteger::LargeInteger(string number) { try {init(number);} catch(LargeIntegerExceptione) {...} } 现在,如果数字是>LargeInteger::MAX_DIGITS(静态常量

我该怎么做

我有一个名为LargeInteger的类,它存储了许多最大20位数字。 我做了构造器

LargeInteger::LargeInteger(string number){ init(number); }
LargeInteger::LargeInteger(string number)
{ try {init(number);} catch(LargeIntegerExceptione) {...} }
现在,如果数字是>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){ init(number); }
LargeInteger::LargeInteger(string number)
{ try {init(number);} catch(LargeIntegerExceptione) {...} }
现在我有两个问题
1.在抛出异常时是否会创建此类的对象?

2.如果上述情况属实,如何处理

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

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


依我看,这是正确的方法-如果无法直接初始化对象,则在构造函数中引发异常,而不创建对象。

否,如果在构造函数中引发异常,则不构造对象(前提是您没有像您一样捕获它)

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


在我看来,这是正确的方法-如果无法直接初始化对象,则在构造函数中引发异常,而不创建对象。

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

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

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

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

那么我在哪里捕捉异常呢?@JeffreyChen,无论你在哪里调用构造函数。那么我在哪里捕捉异常呢?@JeffreyChen,无论你在哪里调用构造函数。