[Tutor] Guidance on using custom exceptions please

Cameron Simpson cs at zip.com.au
Tue Oct 13 17:29:21 EDT 2015


On 13Oct2015 13:43, David Aldrich <David.Aldrich at EMEA.NEC.COM> wrote:
>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.

Without ignoring others' arguments for keeping the full names, you can also go:

  from TxControl import send, MessageTimeoutError, UndefinedMessageTypeError

and just use them unqualified like any other name you might import.

The core issue, to me, is: are the exception names nice and descriptive (they 
look ok to me) and is the module you're using them in not using other 
exceptions of similar name and purpose (i.e. how confusing might the 
unqualified named be)?

Also bear in mind that you can do this:

  from TxControl import send as tx_send, MessageTimeoutError as TxTimeoutError, 
  UndefinedMessageTypeError as TxUndefinedMessageType

which gets you more descriptive names for local use. If course, if these 
exceptions are widely used in many contexts (many other code pieces) then you 
might want to stick with the original names for consistency.

Cheers,
Cameron Simpson <cs at zip.com.au>

Go not to the elves for counsel, for they will say both no and yes.
- Frodo, The Fellowship of the Ring


More information about the Tutor mailing list