C++ C++;异常处理和枚举作用域
我编写了以下异常类:C++ C++;异常处理和枚举作用域,c++,exception,exception-handling,enums,enumeration,C++,Exception,Exception Handling,Enums,Enumeration,我编写了以下异常类: 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() {
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_代码值本质上都是用作错误代码的枚举数值(所有在需要错误检查的单个类中定义的值)
一些示例类:
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;
}
}
}
当来自不同枚举但相同整数值的两个值出现在同一switch case语句中时,我遇到了问题。
当这种情况发生时,就像上面的例子一样,编译器会打印一个“error:duplicate case value”。我想这个错误的原因是
归因于两个家族的整数“性质”。
我怎样才能解决这个问题?我是否必须将此“通用异常方案”更改为多态方案(单一错误类型的一个异常类)?您可以:
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
中定义的枚举(因为不同的枚举数可能成为更改后的最后一个枚举数)。如果这些错误代码必须是唯一的,则必须对这些错误代码使用一个枚举,否则必须执行此操作,第二个枚举以第一个枚举的最后一个值增加1开始。