用模板定义异常是个好主意吗?

时间:2009-01-20 16:04:33

标签: c++ exception templates

我在想是用模板定义异常的好主意。定义不同类型的异常是一个超级详细的任务。你必须继承异常,没有任何改变,只需继承。像这样......

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__))

因此,如果我必须定义一个新的异常,我可以像这样定义一个空类。

class NuclearException {};

抛出异常

THROW(NuclearException , "Boom!!");

抓住

try {

} catch (TemplateException<NuclearException> &e) {
    // ...
}

如果我们想要捕获所有异常,我们可以写这个

try {

} catch (Exception &e) {
   // ...
}

它工作正常,但我不确定是否有任何副作用?定义不同类型的异常是一个好主意吗?还是有更好的解决方案?我不知道:S

感谢。 Victor Lin。

3 个答案:

答案 0 :(得分:3)

这是一个有趣的想法,但除了已经指出的缺点之外,它还不允许您定义异常层次结构:假设您要定义

class InvalidArgumentException {};
class NullPointerException : public InvalidArgumentException {};

然后是TemplatedException&lt; NullPointerException&gt;不会继承TemplatedException&lt; InvalidArgumentException&gt;,并且您的异常处理机制可能最终比“普通”机制更笨拙。

答案 1 :(得分:2)

这绝对有可能并且工作正常,但我会避免它。它模糊了诊断。 GCC将显示异常类型的名称,包括通常的模板内容。我会花几分钟时间来定义新的异常类。这不像你会一直这样做。

答案 2 :(得分:2)

如果你很懒,并且不想写下声明新异常类所需的内容,你可以随时使用一个为你做这个的宏。