Je pense que c'est une bonne idée de définir l'exception avec le modèle. La définition de différents types d'exception est une tâche super verbeuse. Vous devez hériter de l'exception, il n'y a rien de changé, juste hériter. Comme ceci ..Est-ce une bonne idée de définir une exception avec un modèle?
class FooException : public BaseException {
public:
...
};
class BarException : public BaseException {
public:
...
};
...
C'est un cauchemar n'est-ce pas? Donc, j'envisage de définir différentes exception avec le modèle
/**
@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__))
Donc, si je dois définir une nouvelle exception, je peux définir une classe vide comme ça.
class NuclearException {};
à jeter exception
THROW(NuclearException , "Boom!!");
Pour attraper
try {
} catch (TemplateException<NuclearException> &e) {
// ...
}
Si nous voulons prendre toutes les exceptions, nous pouvons écrire ce
try {
} catch (Exception &e) {
// ...
}
Il fonctionne très bien, mais Je ne suis pas sûr qu'il y ait un côté effec ts? Est-ce une bonne idée de définir un type différent d'exception? Ou il y a une meilleure solution? Je n'ai aucune idée: S
Merci. Victor Lin.