What sort of exception when a class can't find something?

Peter J. Holzer hjp-python at hjp.at
Thu Aug 31 16:53:28 EDT 2023


On 2023-08-31 21:32:04 +0100, Chris Green via Python-list wrote:
> What sort of exception should a class raise in __init__() when it
> can't find an appropriate set of data for the parameter passed in to
> the class instantiation?
> 
> E.g. I have a database with some names and address in and have a
> class Person that gets all the details for a person given their
> name.
> 
>      ....
>      ....
>      person.Person('Fred')
>      ...
>      ...
> 
> 
> If Fred doesn't exist in the database what sort of exception should
> there be?  Is it maybe a ValueError?

It you are going for a builtin exception, I think KeyError is the most
appropriate: It should be a LookupError, since the lookup failed and a
database is more like a mapping than a sequence.

But it would probably be best to define your own exception for that.

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20230831/ee234fa7/attachment.sig>


More information about the Python-list mailing list