【问题标题】:Nested try/catch blocks for error propagation across classes?用于跨类传播错误的嵌套 try/catch 块?
【发布时间】:2016-10-07 15:52:12
【问题描述】:

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

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();
     }
};

我想将 'Interface()' 实现包装在 try/catch 块中:

auto Interface()->bool
{
  try{
    this->F1();
    this->F2();
  }catch(...){
     //Handle
  }
}

但是,在发生错误时,我希望再次尝试该函数,如果出现错误,我想将错误传播回父类:

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 块?这是最好的方法吗?

【问题讨论】:

    标签: c++ error-handling try-catch


    【解决方案1】:

    有点像

    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

    【讨论】:

      【解决方案2】:

      这似乎不是孩子应该处理的事情恕我直言,这种行为是否应该由知道如何处理孩子的父母处理?我会走这条路:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 2017-09-30
        • 2022-01-01
        • 2019-04-23
        • 1970-01-01
        • 1970-01-01
        • 2020-08-24
        相关资源
        最近更新 更多