c++ - Why throw a class over an enum? -
just wondering, why better throw class on enum
surely throwing classes more overhead?
e.g.
enum myexception { except_a, except_b, except_c } void function f(){ throw 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 overhead. need declare class each 1 might override std::exception or something. more code, larger binary... what's benefit?
given
enum myexception { except_a, except_b, except_c }
write catch clause catches except_c
exceptions.
with
struct my_except {}; struct my_except_a : my_except {}; struct my_except_b : my_except {}; struct my_except_c : my_except {};
that's easy, since can catch base class or derived classes.
many of common advantages of derivation apply exceptions. example, base classed can stand in derived classes , code needs know base classes deal derived exceptions. that's form of polymorphism, while enum
switch on type.
the general rule polymorphism applies here, too: whenever tempted use switch on type, dismissing advantages of polymorphism. problems getting seen once code has expanded hundreds of kloc, , need add new type. polymorphism, that's easy, because code fine dealing base class references only.
type enum
, have hunt down every single switch
statement on enum
, check whether need adapt it.
things these have killed more 1 company.
here's afterthought: when they've done while, users start add kinds of data exception types. classic take __file__
, __line__
in exception's constructor able see exception came from. this, too, needs exceptions class types.
Comments
Post a Comment