[Tutor] Guidance on using custom exceptions please
Cameron Simpson
cs at zip.com.au
Mon Oct 12 19:59:01 EDT 2015
On 13Oct2015 10:37, Steven D'Aprano <steve at pearwood.info> wrote:
>On Mon, Oct 12, 2015 at 02:55:43PM +0000, David Aldrich wrote:
>> Consider a 'send' method that sends a message to another system via a
>> socket. This method will wait for a response before returning. There
>> are two possible error conditions:
>[...]
>> So, my question is, what's the pythonic way of doing this? Should I
>> subclass RuntimeError for each possible error condition? E.g.:
>>
>> class MessageTimeoutError(RuntimeError): pass
>> class IllegalResponseError(RuntimeError): pass
>
>I don't think you should be subclassing RuntimeError at all. I'm not
>quite sure what exception you should subclass, but I am confident it
>shouldn't be RuntimeError.
>
>Help on class RuntimeError in module exceptions:
>
>class RuntimeError(StandardError)
> Unspecified run-time error.
I tend to use RuntimeError for program logic errors (code paths that shoudn't
happen, like not handling an option combination). I would not use it for this.
>Since you are working with sockets, I think a socket error might be most
>useful:
>
>import socket # which I expect you are already doing
>
>class MessageTimeoutError(socket.error): pass
>class IllegalResponseError(socket.error): pass
>
>Or possibly inherit from the same exception class that socket.error
>inherits from: IOError.
I have mixed feeling about this; I feel that socket.error or IOError should
reflect actual OS level or IO subsystem errors, not higher level program
discrepancies such as invalid packet data. I would be included to subclass
StandardError.
Antipattern example: I discovered yesterday that PILLOW raises OSError when it
doesn't recognise an image file's content. I consider that a bad choice; I'd
prefer ValueError probably - there's been no OS level failure like lack of
permission to open the file.
On that basis, I recommend either just raising a ValueError for an invalid
packet or subclassing it.
>I'm not certain that you actually need MessageTimeoutError since the
>socket module itself already defines a socket.timeout error that will be
>raised on a timeout. Just re-use that.
That seems reasonable, if he's using the recv timeout facility.
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Tutor
mailing list