[Tutor] Guidance on using custom exceptions please

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Tue Oct 13 17:11:12 EDT 2015


On 13.10.2015 15:43, David Aldrich wrote:
 >
> 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?
>

In simple cases, I would just refer to them as you describe.
If things get more complex, you may want to refactor your code into a 
package anyway, in which case you can define your complete exception 
hierarchy in __init__.py (or in another dedicated module) and import 
them from there whenever you need them in other modules.




More information about the Tutor mailing list