Re: Try..Except..Else

Tim Peters (tim@ksr.com)
Sat, 11 Dec 93 02:39:25 EST

> try:
> file = open('...', 'r')
> data = process_file(file)
> except IOError:
> data = process_something_else()
>
> Is proper.

John, Jaap's problem with this is that it will hide an IOError exception
raised by process_file(file). If he doesn't intend the "except" block to
catch IOErrors raised by process_file (and he said he doesn't, so let's
take that as given), this way of writing it simply doesn't work. BTW,
catching an exception you didn't _expect_ to catch is a genuine source of
subtle bugs in practice; I believe that's what Jaap is trying to address
here (or, at least, that's what I'd like to solve & I believe Jaap's
"else:" suggestion pretty much does the trick).

> If you want code to only execute if a exception dosent happen, then
> thats what the try body is for.

Well, that's one use for a try body. But, as above, it's often unsafe,
or just too clumsy, to use a try body for this purpose.

> [suggesting]
> if (file = open('...', 'r'))
> then
> data = process_file(file)
> else
> data = process_something_else()

This style works in other languages, but Python's open raises IOError if,
e.g., '...' does not exist. So this way of writing it doesn't work in
Python. If you want to argue that Python's open should non-exceptionally
return a failure value instead, fine, but that's a different topic
(although I'd bet most Python slingers are much happier with an exception
than a failure value in this context (why? because failure in this
context is exceptional <0.6 grin>)).

> If you want to execute code UNconditionally after a try block, use
> Try..Finally.

No argument here <wink>!

harmoniously y'rs - tim

Tim Peters tim@ksr.com
not speaking for Kendall Square Research Corp