[Tutor] Guidance on using custom exceptions please

Danny Yoo dyoo at hashcollision.org
Tue Oct 13 14:41:20 EDT 2015


On Mon, Oct 12, 2015 at 7:55 AM, David Aldrich
<David.Aldrich at emea.nec.com> 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:
>
> 1)      Timeout - i.e. no response received
>
> 2)      Illegal response received
>
> I need to communicate these errors to the caller of send().  So far I have just raised a RuntimeError exception for both errors, and stated what happened like this:
>
> raise RuntimeError("Message timeout")


Hi David,

According to:

    https://docs.python.org/3.5/library/exceptions.html

you can subclass the "Exception" class.

    https://docs.python.org/3.5/library/exceptions.html#Exception

That's the one that you probably should subclass from, as you're
defining your own "non-system-exiting" exception.  It's
"non-system-exiting" because you expect the caller to have to do some
special behavior when receiving such a condition.

Use Exception as your base.  As Peter Otten describes, you can create
your own hierarchy as necessary, but anchor it from Exception first.

RuntimeError is for something that doesn't fit any of the other
categories used by the Standard Library:

    https://docs.python.org/3.5/library/exceptions.html#concrete-exceptions

As such, it's probably not something you yourself should be using as a
subclass.  You'd expect to see RuntimeError if something truly unusual
is happening within the Python runtime environment.  But that's not
the case for the exceptions you're describing: timeout and illegal
arguments are application-level exceptions, not low-level Python
runtime environmental problems.


Hope that clears things up!


More information about the Tutor mailing list