Proper way to handle errors in a module

MRAB python at mrabarnett.plus.com
Thu May 12 15:25:21 EDT 2011


On 12/05/2011 20:14, Andrew Berg wrote:
> On 2011.05.11 01:05 PM, Roy Smith wrote:
>> You want to raise specific errors.  Let's say you've got a function like
>> this:
>>
>> def airspeed(swallow):
>>     speeds = {"european": 42,
>>               "african", 196}
>>     return speeds[swallow]
>>
>> If somebody passes an invalid string, it will raise KeyError as written.
>> Better to do something like:
>>
>> def airspeed(swallow):
>>     speeds = {"european": 42,
>>               "african", 196}
>>     try:
>>         return speeds[swallow]
>>     except KeyError:
>>          raise UnknownBirdError(swallow)
> Is there any way to do this without purposely setting up the code to
> trigger an arbitrary exception if the function can't do its job? That
> is, can I raise an UnknownBirdError outside of an except clause, and if
> so, how? I can't find much help for doing this in Python 3, even in the
> official docs.
 >
You can raise an exception wherever you like! :-)



More information about the Python-list mailing list