Are nested try/except blocks in Python a good programming practice?
Your first example is perfectly fine. Even the official Python documentation recommends this style known as EAFP.
Personally, I prefer to avoid nesting when it's not necessary:
def __getattribute__(self, item):
try:
return object.__getattribute__(item)
except AttributeError:
pass # Fallback to dict
try:
return self.dict[item]
except KeyError:
raise AttributeError("The object doesn't have such attribute") from None
PS. has_key()
has been deprecated for a long time in Python 2. Use item in self.dict
instead.
While in Java it's indeed a bad practice to use exceptions for flow control (mainly because exceptions force the JVM to gather resources (more here)), in Python you have two important principles: duck typing and EAFP. This basically means that you are encouraged to try using an object the way you think it would work, and handle when things are not like that.
In summary, the only problem would be your code getting too much indented. If you feel like it, try to simplify some of the nestings, like lqc suggested in the suggested answer above.
Just be careful - in this case the first finally
is touched, but skipped too.
def a(z):
try:
100/z
except ZeroDivisionError:
try:
print('x')
finally:
return 42
finally:
return 1
In [1]: a(0)
x
Out[1]: 1