C++异常处理和枚举作用域

C++ Exception Handling and Enum Scoping

本文关键字:作用域 枚举 异常处理 C++      更新时间:2023-10-16

我编写了以下异常类:

class generic_exception : public std::exception
{
  public:
    generic_exception( std::string where, int err_code , bool fatal ) 
    : where_(where) , errcode_(err_code) ,fatal_(fatal) {}
      inline int get_errcode()
      {
        return errcode_;
      }
      inline bool is_fatal()
      {
        return (fatal_ == true ? true : false);
      }
      inline std::string get_where()
      {
        return where_;
      }
     ~generic_exception() throw () { }
  private:
    std::string where_;
    int errcode_;
    bool fatal_;
};

我使用它来处理错误,而没有为每种类型的错误创建一个异常类。所有err_code值本质上都是用作错误代码的枚举器值(在中定义的所有需要错误检查的类中)。

一些示例类:

class A
{
  enum one{a,b,c}
};
class B
{
  enum two{d,e,f}
};

尝试捕获示例:

try
    {
      //something
      throw generic_exception("where" , one::a , true );
      throw generic_exception("where" , two::a , true );
    }
    catch( generic_exception e)
    {
      switch(e.get_errcode())
      {
        case one::a:
          break;
        case two::b:
          break;
      }
    }
  }

当来自不同枚举但相同整数值的两个值出现在同一个switchcase语句中时,我遇到了问题。当这种情况发生时,就像上面的例子一样,编译器会打印一个"错误:重复的大小写值"。我想这个错误的原因是归因于这两个家族的整数性质。我该如何解决这个问题?我是否必须将这个"通用异常方案"更改为多态方案(单个错误类型的一个异常类)?

您可以:

1)使用全局枚举:

enum ErrorCode
{
    A_one,
    A_two,
    A_three,
    //...
    B_one,
    B_two,
    //...
};

2)或使用枚举器计数:

class A
{
public:
    enum
    {
        Err_one,
        Err_two,
        Err_three,
        //...
        Last_error
    };
};
class B
{
public:
    enum
    {
        Err_one = A::Last_error,
        Err_two,
        Err_three,
        //...
        Last_error
    };
};

Last_error的技巧很好,因为您可以用这种方式定义许多枚举器,如果您添加/删除一些枚举器,它们都不需要更新。若要避免定义额外的枚举器,则应将上一个枚举中最后一个枚举器的值分配给第一个枚举器,增加1。

但请注意,在这种情况下,即使A中定义的枚举发生微小变化,也可能需要更新类B中定义的enum(因为不同的枚举器可能会成为更改后的最后一个枚举器)。