Best Practices for Python Exceptions?

后端 未结 5 835
北恋
北恋 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:44

    I read several times in books that exceptions should never ever hold a string, because strings themselves can throw exceptions. Any real truth to this?

    What?

    Please provide a reference or a link to this. It's totally untrue.

    Since all objects can throw exceptions, no object could be contained in an exception by that logic.

    No, the "no strings" is simply crazy in a Python context. Perhaps you read it in a C++ context.


    Edit

    Once upon a time (back in the olden days) you could raise a Python exception by name instead of by the actual class.

    raise "SomeNameOfAnExceptionClass"
    

    This is bad. But this is not including a string inside an exception. This is naming the exception with a string instead of the actual class object. In 2.5, this can still work, but gets a deprecation warning.

    Perhaps this is what you read "Do not raise an exception with a string name"

提交回复
热议问题