嵌套的try/catch块用于跨类传播错误

Nested try/catch blocks for error propagation across classes?

本文关键字:传播 错误 用于 try catch 嵌套      更新时间:2023-10-16

我有一个类接口函数,它以特定的顺序在类中实现其他函数:

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