【发布时间】:2015-04-10 12:52:54
【问题描述】:
我写了以下异常类:
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;
}
}
}
当来自不同枚举但相同整数值的两个值出现在同一个 switch case 语句中时,我遇到了问题。 当这种情况发生时,就像上面的例子一样,编译器会打印一个“错误:重复的大小写值”。我猜这个错误的原因是 归因于两个家庭的整数“性质”。 我怎么解决这个问题?我是否有义务将这种“通用异常方案”更改为多态方案(单一错误类型的一个异常类)?
【问题讨论】:
-
如果这些错误代码必须是唯一的,您将不得不对这些错误代码使用一个枚举,否则您将不得不做的伎俩,即第二个枚举从您的第一个枚举的最后一个值开始增加1.
标签: c++ exception exception-handling enums enumeration