Just wondering, why is it better to throw a class over an enum
Surely throwing classes is more overhead?
e.g.
enum MyException
{
except_a,
except_b,
except_c
}
void function f(){
throw except_a;
}
int main(int arc, char* argv[]){
try{
} catch (MyException e){
switch(e){
except_a: break;
except_b: break;
except_c: break;
}
}
return 0;
}
Apart from the overhead. I also need to declare a class for each one which might override std::exception or something. More code, larger binary… what’s the benefit?
Given
write a catch clause that only catches
except_cexceptions.With
that’s easy, since you can catch the base class or derived classes.
Many of the common advantages of derivation apply to exceptions. For example, base classed can stand in for derived classes and code needs to know only base classes to deal with derived exceptions. That’s a form of polymorphism, while the
enumis a switch over a type.The general rule about polymorphism applies here, too: Whenever you are tempted to use a switch over a type, you are dismissing the advantages of polymorphism. The problems you are getting yourself into will be seen once the code has expanded to hundreds of kLoC, and you need to add a new type. With polymorphism, that’s easy, because most code will be fine dealing with base class references only.
With the type
enum, you have to hunt down every singleswitchstatement over thatenumand check whether you need to adapt it.Things like these have killed more than one company.
Here’s an afterthought: When they’ve done this for a while, users usually start to add all kinds of data to their exception types. A classic is to take
__FILE__and__LINE__in an exception’s constructor to be able to see where an exception came from. But this, too, needs exceptions to be class types.