In Python, how can I use except block with same exception name twice in try/except statements without need to wrap code into one more try/except block?
Simple example (here each call of pages.get may raise the exception):
try:
page = pages.get(lang=lang)
except Page.DoesNotExist:
if not lang == default_lang:
page = pages.get(lang=default_lang)
else:
raise Page.DoesNotExist
except Page.DoesNotExist:
page = pages[0]
For now, in my Django app I do handling like this (but I don’t want “extra” try block here):
try:
try:
page = pages.get(lang=lang)
except Page.DoesNotExist:
if not lang == default_lang:
page = pages.get(lang=default_lang)
else:
raise Page.DoesNotExist
except Page.DoesNotExist:
page = pages[0]
Any handling code better than above is appreciated! 🙂
Thanks.
You can’t do this either and expect the
elifto execute:And there’s no reason to do this, really. Same for your
exceptconcern.Here’s the disassembled Python bytecode of your first code snippet:
It’s obvious that the first
COMPARE_OPtoNameError(at offset 17) will catch the exception and jump to after the second such comparison (at offset 36).