Exception as the primary error handling mechanism?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Jan 4 07:55:01 CET 2010

On Sun, 03 Jan 2010 22:36:44 -0500, Roy Smith wrote:

> In article <pan.2010. at REMOVE.THIS.cybersource.com.au>,
>  Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> wrote:
>> This last one can be *very* problematic. In the early 1990s, I was
>> programming using a callback API that could only return an integer. The
>> standard way of indicating an error was to return -1. But what happens
>> if -1 is a legitimate return value, e.g. for a maths function?
> One of the truly nice features of Python is the universally
> distinguished value, None.

What happens if you need to return None as a legitimate value?

Here's a good example: iterating over a list. Python generates an 
exception when you hit the end of the list. If instead, Python returned 
None when the index is out of bounds, you couldn't store None in a list 
without breaking code.

So we produce a special sentinel object EndOfSequence. Now we can't do 

for obj in ["", 12, None, EndOfSequence, [], {}]:
    print dir(obj)  # or some other useful operation

The fundamental flaw of using magic values is that, there will always be 
some application where you want to use the magic value as a non-special 
value, and then you're screwed.

This is why, for instance, it's difficult for C strings to contain a null 
byte, and there are problems with text files on DOS and CP/M (and Windows 
under some circumstances) that contain a ^Z byte.


More information about the Python-list mailing list