Proper way to handle errors in a module

Andrew Berg bahamutzero8825 at gmail.com
Thu May 12 15:14:22 EDT 2011


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.



More information about the Python-list mailing list