嵌套的try/catch块用于跨类传播错误
Nested try/catch blocks for error propagation across classes?
我有一个类接口函数,它以特定的顺序在类中实现其他函数:
class Child
{
public:
auto Interface()->bool
{
this->F1(); //I use this just for extra clarity (e.g. not calling global function)
this->F2();
return true;
}
auto F1()->void
{
//Do stuff...
}
auto F2()->void
{
//Do more stuff...
}
};
class Parent
{
public:
Child ChildObj;
auto CallUponChild()->void
{
bool success = ChildObj.Interface();
}
};
我想在try/catch块中包装'Interface()'实现:
auto Interface()->bool
{
try{
this->F1();
this->F2();
}catch(...){
//Handle
}
}
但是,在出现错误时,我希望再次尝试该函数,如果出现错误,我希望将错误传播回Parent类:
auto Interface()->bool
{
int error_count=0;
try{
try{
this->F1();
this->F2();
return true;
}catch(...){
if(error_count<1){this->F1(); this->F2();}
else{throw "Out of tries";}
}
}catch(...){
return false;
}
}
是否使用嵌套的try/catch块?这是最好的方法吗?
类似
auto Interface()->bool
{ int error_count=0;
while (error_count < 1) {
try {
this->F1();
this->F2();
return true;
}
catch(...){
// if (error_count >= 1)
// throw; // to throw original exception
++error_count;
}
};
// throw "Out of tries"; // to throw "Out of tries" exception
return false; // to use the boolean result
}
应该足够。如果F1()
在catch块中抛出异常,则函数将返回false
而不增加error_count
。
这似乎不是孩子应该处理的事情,这种行为应该由知道如何处理孩子的父母来处理吗?我会这样写:
auto CallUponChild()->void
{
const bool success = ChildObj.Interface();
if (!success) { // maybe if-init if you have a c++17 compiler
// try again
ChildObj.Interface();
}
}
我认为处理子对象的方式应该在父级,就像我说的,子对象应该做一件事,如果需要做两次(或N次),那么不应该是他们的责任。
如果你想显示异常是如何被抛出的,你可以看一下:
http://en.cppreference.com/w/cpp/error/throw_with_nested相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 嵌套的try/catch块用于跨类传播错误
- Boost Python,传播c++回调到Python导致分段错误
- c++错误代码传播