Tip 90 Isolate Exceptions
Pythonic Programming — by Dmitry Zinoviev (103 / 116)
👈 Treat Variables as References | TOC | Compare Prefixes and Suffixes 👉
★★★2.7, 3.4+ Exception handling is a powerful protection mechanism against run-time errors. Just like any powerful mechanism, it may and often is misused. One sort of misuse is not handling any exceptions. The other one is handling all exceptions at once with one blanket try-except statement:
try:
# All your code (including 0/0, [][0], and 'hello'-'world')
except:
exit()
While the second approach seems safer (the program never crashes), it hides all possible errors from the developer, creating an illusion of a perfect program.
The Pythonic rule of thumb is that you should protect only the statements that can raise an exception. If a statement can raise more than one type of exception, you should handle each type separately (unless you use the recovery action for all or some exception types). For example, the open function may fail because the requested file is not found, or is a directory, or cannot be read, or for some other reason. Protect the function properly:
try:
with open('somefile.txt') as infile:
# Read the file
except (FileNotFoundError, IsADirectoryError, PermissionError):
# These are specific errors that you may be able to handle
# Handle them!
except IOError:
# These are other…