exception handling in complex Python programs

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Aug 20 15:24:59 CEST 2008

On Tue, 19 Aug 2008 22:24:45 -0700, eliben wrote:

> """ between file()
> and open() in Python 2 and 3, a NameError is thrown with open() in
> Python 3 and an IOError is thrown in the other three cases <bashes head
> against keyboard>.
> """

I'm curious about the claim that open() will raise NameError in Python3. 
I find it hard to credit that claim, but if it is correct, what's the 
justification for that?

> This is *exactly* my concern with Python exceptions. You just never know
> what can be thrown at you.

It's true that documentation of exceptions is relatively weak in Python. 
And some functions can raise a bewildering array of exceptions. See for 
example this thread where somebody notes that urllib2.urlopen() can raise 
any of six different exceptions:


And I've had it raise socket.error, which makes seven. And the 
documentation only mentions one of those exceptions.

However, as Gregory Smith describes, some of those seven exceptions are 
subclasses of others, so it is possible to reduce it down to three cases 
-- and arguably one of those cases (ValueError) is a bug that needs 
fixing, not an exception that needs catching.

That's probably as bad as it gets in Python, at least for the standard 
library. Most functions don't raise arbitrary exceptions for sensible 
data, and if you pass non-sensible data then you should treat the 
exception as a bug in your code and fix it.


More information about the Python-list mailing list