C++ 用模板定义异常是个好主意吗?
我认为用模板定义异常是个好主意。定义不同类型的异常是一项非常冗长的任务。您必须继承异常,没有任何更改,只是继承。像这样C++ 用模板定义异常是个好主意吗?,c++,exception,templates,C++,Exception,Templates,我认为用模板定义异常是个好主意。定义不同类型的异常是一项非常冗长的任务。您必须继承异常,没有任何更改,只是继承。像这样 class FooException : public BaseException { public: ... }; class BarException : public BaseException { public: ... }; ... 那是一场噩梦,不是吗?所以我考虑用模板定义不同的异常 /** @brief Exception of ra
class FooException : public BaseException {
public:
...
};
class BarException : public BaseException {
public:
...
};
...
那是一场噩梦,不是吗?所以我考虑用模板定义不同的异常
/**
@brief Exception of radio
**/
class Exception : public runtime_error {
private:
/// Name of file that throw
const string m_FileName;
/// Line number of file that throw
size_t m_Line;
public:
Exception(const string &what, const string &File, size_t Line)
throw()
: runtime_error(what),
m_FileName(File),
m_Line(Line)
{}
virtual ~Exception() throw() {}
/**
@brief Get name of file that throw
@return Name of file that throw
**/
virtual const string getFileName() const throw() {
return m_FileName;
}
/**
@brief Get throw exception line
@return Throw exception line
**/
virtual size_t getLine() const throw() {
return m_Line;
}
/**
@brief Get description of this exception
@return Description of this exception
**/
virtual const string getMessage() const throw() {
return what();
}
virtual void print(ostream &stream = cerr) const throw() {
stream << "# RunTimeError #" << endl;
stream << "Error : " << what() << endl;
stream << "File : " << getFileName() << endl;
stream << "Line : " << getLine() << endl;
}
};
/**
@brief Template exception of radio
**/
template <typename T>
class TemplateException : public Exception {
public:
TemplateException (const string &what, const string &File, size_t
Line) throw()
: Exception(what, File, Line)
{}
virtual ~TemplateException () throw() {}
};
}
#define THROW(type, error) (throw TemplateRadioException<type>(
(error), __FILE__, __LINE__))
抛出异常
THROW(NuclearException , "Boom!!");
捉住
try {
} catch (TemplateException<NuclearException> &e) {
// ...
}
它很好用,但我不确定有没有副作用?定义不同类型的异常是个好主意吗?还是有更好的解决办法?我不知道:S
谢谢。
Victor Lin.这肯定是可能的,而且效果很好,但我会避免它。它模糊了诊断。GCC将显示异常类型的名称,包括通常的模板内容。我个人会花几分钟来定义新的异常类。这并不是说你会一直这么做。如果你很懒,不想编写声明新异常类所需的内容,你可以随时使用一个宏来完成它。这是一个有趣的想法,但除了已经指出的缺点,它也不允许您定义异常层次结构:假设您要定义
class InvalidArgumentException {};
class NullPointerException : public InvalidArgumentException {};
然后TemplatedException将不会从TemplatedException继承,并且您的异常处理机制可能会比“普通”机制更加笨拙
try {
} catch (Exception &e) {
// ...
}
class InvalidArgumentException {};
class NullPointerException : public InvalidArgumentException {};