Limit Your Try Clauses in Python2019-10-02
Take this code:
The intention of the
try … except statement is catch the potential
KeyError from accessing
get_parrot(), or any function they call use dictionaries, they might also raise
˙KeyError, perhaps due to a bug.
With the code as it is, such errors will be silently ignored.
parrot would be set to
None, even though
name was found, and the program would continue… possibly to destruction!
Instead, we should limit our
try clause to the lines that can raise the expected error.
Python lets us do this with the
Simpler and clearer.
This is as per the Handling Exceptions documentation:
The use of the else clause is better than adding additional code to the
tryclause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the
try … exceptstatement.
try to write better code,
© 2019 All rights reserved.