[Tutor] Guidance on using custom exceptions please

David Aldrich David.Aldrich at EMEA.NEC.COM
Tue Oct 13 09:43:27 EDT 2015


> If you don't want to let the original timeout error bubble up you can create
> your own little hierarchy of exceptions:
> 
> class ResponseError(Exception):
>     pass
> 
> class TimeoutError(ResponseError):
>     pass
> 
> class BadDataError(ResponseError):
>     pass
> 
> Then the baseclass of ResponseError doesn't matter much as client code that
> wants to catch every expected error can catch ResponseError. You can later
> add subclasses as needed without breaking this catch-all client.

Thanks for all the answers to my question, they were all helpful.

I have one more question, which regards style.  Suppose my 'send' method is in its own module: TxControl, along with the custom exceptions:

TxControl.py:

class MessageTimeoutError(Exception): pass
class UndefinedMessageTypeError(Exception): pass

def send(msg)
     etc.

Then it seems that an importer of that module must include the module name when referencing the exceptions:

import TxControl

try:
    send(msg)
except (TxControl.MessageTimeoutError, TxControl.UndefinedMessageTypeError) as err:
    # Exception processing

Including 'TxControl' seems a bit tedious, and is even worse if TxControl imports exceptions from yet another module and allows them to pass up the stack.

How would you handle this situation stylistically?

David


More information about the Tutor mailing list