异常处理C++
Exception-Handling C++
我该怎么做,
我有一个名为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.
相关文章:
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- 使用 stoi 功能进行异常处理
- 子系统中的异常处理:本机
- 与异常处理程序中的操作员<<不匹配
- 数组 C++ 上的异常处理程序
- 异常处理:如果用户输入不是三个特定字符之一
- C++ 异常处理错误输出
- 视觉 std::矢量无异常:警告 C4530:使用了C++异常处理程序,但未启用展开语义.指定 /EHsc
- C++交换机状态异常处理
- 在字符串类上的成员函数和out_of_range异常处理
- 奇怪的消息 (_Base_bitset::_M_do_to_ulong) 从溢出异常处理程序中打印出来
- 执行视觉工作室异常处理模式
- 为什么隐式转换在异常处理中从派生到基?
- C++执行期间的类成员函数错误/异常处理
- C++ 中未处理的异常处理程序
- 用户定义的异常处理
- C :ScopeGuard vs返回支票和异常处理
- 异常处理期间的类型解析