Python one exception multiple handlers -
i want this:
try: raise a() except a: print 'a' except (a, b): print 'a,b' which hoped print both a , a,b.
that doesn't work (only first except executed). makes sense first except swallow error, in case want catch subclass before it's parent.
but there elegant way work?
i of course following, seemingly redundant code duplication, if more a , b involved:
try: raise a() except a: print 'a' print 'a,b' except b: print 'a,b' (related multiple exception handlers same exception not duplicate. usage different , want know how best handle minimal code duplication.)
it's rather common catch possible exceptions , exception type instance later:
try: raise a() except (a, b) e: if isinstance(e, a): print('a') print('a', 'b') another option inherit 1 class e.g.
class b(exception): def do(self): print('a', 'b') class a(b, exception): def do(self): print('a') super().do() then
try: raise b() except (a, b) e: e.do() will print a b, ,
try: raise a() except (a, b) e: e.do() will print a , a b.
Comments
Post a Comment