Given a base exception type:
class MyModuleError(Exception):
pass
Suppose we have code that explicitly raises it, using exception chaining:
def foo():
try:
#some code
except (ZeroDivisionError, OSError) as e:
raise MyModuleError from e
Now, in the calling code...
try:
foo()
except MyModuleError as e:
# Now what?
how can I idiomatically write the except
clause, so that the exception handling depends on the __cause__
(chained exception)?
I thought of these approaches:
a) using type(e)
like:
# filter here
t=type(e.__cause__)
if t is ZeroDivisionError:
doStuff()
elif t is OSError:
doOtherStuff()
else:
raise
b) using isinstance()
like:
# filter here
if isinstance(e.__cause__, ZeroDivisionError):
doStuff()
elif isinstance(e.__cause__, OSError):
doOtherStuff()
else:
raise
c) re-raising like:
# filter here
try:
raise e.__cause__
except ZeroDivisionError:
doStuff()
except OSError:
doOtherStuff()
except:
raise e #which should be the "outer" exception