[Tutor] Guidance on using custom exceptions please
Steven D'Aprano
steve at pearwood.info
Mon Oct 12 19:37:01 EDT 2015
On Mon, Oct 12, 2015 at 02:55:43PM +0000, David Aldrich wrote:
> Hi
>
> 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.
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'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.
--
Steve
More information about the Tutor
mailing list