I'm currently building a C++ game engine as a learning exercise, and am incorporating exceptions into the less performance-critical sections. I'm primarily a PHP and Ruby developer, so I'm used to declaring new classes of exception on a regular basis using simple syntax like this:
class SomeSubSystemException < Exception; end
or
class SomeSubSystemException extends Exception {};
is there an easy syntax for doing this in C++, or am I going about exception handling the wrong way for C++ projects? Currently I have to do the following for every class of exception, which makes me want to not define very many:
class SubSystemException : public MainException {
SubSystemException(std::string& msg) : MainException(msg) {}
};
Thanks in advance!
Define a Macro that does that for you.
#define NEW_EXC(Derived, Base) class Derived : Base {\
Derived(const std::string& msg) : Base(msg) {}
NEW_EXC(SubSystemException, MainException);
#undef NEW_EXC
Done.
Although I agree with the comment from Bo Person saying that this will not be your main source of boilaerplate, here another way for the heck of it:
Use CRTP
template<class T>
class MainException : public std::runtime_error{
private:
MainException(std::string const& msg):std::runtime_error(msg){ }
public:
static MainException<T> create(std::string const& msg){
return MainException<T>(msg);
}
};
//Usage:
class MyException : public MainException<MyException> {};
void foo(){
MyException::create(std::string("Foo"));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.