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

Fan*_*Lin 5 c++ templates exception

我在想用模板定义异常是个好主意。定义不同类型的异常是一项非常冗长的任务。你必须继承异常,没有什么改变,只是继承。像这样..

class FooException : public BaseException {
public:
    ...
};

class BarException : public BaseException {
public:
    ...
};

...
Run Code Online (Sandbox Code Playgroud)

那是一场噩梦,不是吗?所以我正在考虑用模板定义不同的异常

/**
    @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__))
Run Code Online (Sandbox Code Playgroud)

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

class NuclearException {};
Run Code Online (Sandbox Code Playgroud)

抛出异常

THROW(NuclearException , "Boom!!");
Run Code Online (Sandbox Code Playgroud)

去抓

try {

} catch (TemplateException<NuclearException> &e) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

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

try {

} catch (Exception &e) {
   // ...
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢。维克多·林。

Joh*_*itb 2

这绝对是可能的并且工作得很好,但我会避免它。它掩盖了诊断。GCC 将显示异常类型的名称,其中包括常用的模板内容。我个人会花几分钟来定义新的异常类。这不像你会一直这样做。