Exception handling in Python is a tremendously useful feature. I grew up on C programming, where, to write a really "correct" program, it seems like you have to spend half your code on mundane error checking.
for(i=0; i<NR; ++i) {
result = do_thing_1();
if (result < 0) {
if (result == IO_ERROR) {
/* handle error */
}
else if (result == API_ERROR) {
/* handle error */
}
else {
/* handle unknown error */
}
}
result = do_thing_2();
/* sigh ... I have to code another huge error block ... */
...
/* finally, the loop ends! */
}
True, C++ has exception handling, but if you are calling standard C-library functions, then you have to go back to the mundane way.
Rewriting the above mess into an equivalent Python block gives:
try:
# uninterrupted program logic here, no need to break up
# the natural flow with error checking
for i in range(NR):
do_thing_1()
do_thing_2()
# errors can all be handled out-of-line
except IOERROR:
# handle IO error
except API_ERROR:
# handle API error
except:
# handle unknown error
# ** be careful here -- keep reading! **
Notice that I wrote
"be careful here" under the last
except clause. The "be careful" part is what I want to cover in this article. The topics I'm going to cover are:
- Globally catching unhandled errors.
- Catching exceptions, with details.
- Catching multiple exceptions.
- When it is bad/good to use "bare" exceptions.