Exception as the primary error handling mechanism?

Lie Ryan lie.1296 at gmail.com
Wed Jan 6 13:20:41 EST 2010


On 1/7/2010 2:12 AM, Phlip wrote:
> On Jan 5, 10:54 pm, Benjamin Kaplan<benjamin.kap... at case.edu>  wrote:
>
>> {41: None}[41] ?
>>
>> In cases where None is a valid result, you can't use it to signal failure..
>
> Asked and answered. You change the "sentinel" in .fetch to something
> else.

I believe Ben Kaplan's point is that if dict slicing returns sentinel 
for missing keys, the slicing syntax would be unusable to differentiate 
{41: sentinel} and {}; if the default sentinel had been None, that would 
make it too easy to forget to reset the sentinel and wrote a buggy code.

> But y'all keep on defending the language making your programming
> decisions for you!

When designing a language, there are two different ways to signal a 
missing key in a dict: 1) raise an exception or 2) return a sentinel. 
Both are useful for different purpose. One or the other must be the 
default behavior, and the other must give way.

Python decided that the default behavior should be raising exception and 
sentinel have to use the dict.get() method. Simple and clear. The other 
possible behavior (i.e. slicing returns a sentinel while dict.get() 
raises an exception) is arguably just as simple and just as clear; but 
python doesn't do it that way. Why? Because it's part of what makes 
python Python[1].

> But y'all keep on defending the language making your programming
> decisions for you!

Indeed, the language makes decisions for you; why would you want to use 
a language that nags you for every possible different behavior? I want a 
reasonable default and I want a reasonably easy way to access the 
non-default behaviors.

[1] the essence of which is emboldened as the Zen, which is the broad 
design guideline for both python's syntax and codes written in python. 
Specifically, "Errors should never pass silently" because missing key 
indicates a possible error and "Simple is better than complex" because 
returning sentinel for missing keys implies the need for an interface to 
change the sentinel[2].
[2] or become like Java, whose HashMap cannot reliably store null and 
doesn't allow you to specify the sentinel.



More information about the Python-list mailing list