创建异常的最佳做法是什么?刚看到这个,不知道是应该惊恐还是喜欢。我在书中多次读到异常永远不应该包含字符串,因为字符串本身可以抛出异常。这有什么真实的吗?
基本上,根据我对脚本的理解,这样做是为了让所有内部 Python 库都有一个通用的错误消息格式(迫切需要的东西),所以我可以理解为什么放置错误消息字符串是个好主意。 (几乎每个方法都会抛出异常,因为完全不需要任何无效的通过)。
有问题的代码如下:
"""
Base Exception, Error
"""
class Error(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return "[ERROR] %s\n" % str(self.message)
def log(self):
ret = "%s" % str(self.message)
if(hasattr(self, "reason")):
return "".join([ret, "\n==> %s" % str(self.reason)])
return ret
class PCSException(Error):
def __init__(self, message, reason = None):
self.message = message
self.reason = reason
def __str__(self):
ret = "[PCS_ERROR] %s\n" % str(self.message)
if(self.reason != None):
ret += "[REASON] %s\n" % str(self.reason)
return ret
这只是冰山一角,但是有人可以告诉我是什么让这个想法变得糟糕吗?或者,如果有更好的异常编码流程/风格。
最佳答案
Robust exception handling (in Python) - 我不久前写的一篇“Python 异常的最佳实践”博文。您可能会发现它很有用。
博客中的一些关键点:
Never use exceptions for flow-control
Exceptions exist for exceptional situations: events that are not a part of normal execution.
如果未找到模式,请考虑对返回 -1 的字符串进行“查找”,但超出字符串末尾的索引会引发异常。找不到字符串是正常执行。
Handle exceptions at the level that knows how to handle them
...
The best place is that piece of code that can handle the exception. For some exceptions, like programming errors (e.g. IndexError, TypeError, NameError etc.) exceptions are best left to the programmer / user, because "handling" them will just hide real bugs.
总是问“这是处理这个异常的正确地方吗?”并小心捕捉所有异常。
Document the exceptions thrown by your code
...
thinking about which exceptions your code may throw will help you write better, safer and more encapsulated code
关于python - Python 异常的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/839636/