Best Practices for Python Exceptions?

后端 未结 5 829
北恋
北恋 2021-01-29 20:04

What are the best practices for creating exceptions? I just saw this, and I don\'t know if I should be horrified, or like it. I read several times in books that exceptions shoul

5条回答
  •  一整个雨季
    2021-01-29 20:31

    First impression is that it's entirely too much code for an exception.

    Formatting exceptions should be done in logger configuration. Same goes for the logging itself.

    It also redefines the standard (and deprecated) message attribute, and doesn't call the superclass constructor. (This might or might not break Python 3.0 exception chaining, I haven't tried because I'm running 2.6)

    Most of what the extra code does can be realised using BaseException.args, by logging the following as the "message":

    '\n==> '.join(exception.args)
    

    I'd argue that if something can be done using a common / idiomatic mechanism, it should especially be done so in exception handling. (Exceptions being a mechanism to signal something across application layers.)

    Personally, I try to avoid anything beyond

    class SomeException(Exception): pass
    

    (Disclaimer: answer subjective, possibly by nature of the question.)

提交回复
热议问题