如何判断要使用的错误类型(例如TypeError
,ValueError
)?
我知道我可以选择,但是根据上下文,某些选项比其他选项更相关吗?
示例:由于节点等级限制而无法在图形上添加边(我希望它是一个错误,而不仅仅是 bool(boolean) 值,它表示失败)
最佳答案
您可以在此处找到所有默认异常的描述:https://docs.python.org/3/library/exceptions.html
例如,
TypeError
Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.
This exception may be raised by user code to indicate that an attempted operation on an object is not supported, and is not meant to be. If an object is meant to support a given operation but has not yet provided an implementation, NotImplementedError is the proper exception to raise.
Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError.
ValueError
Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
但是,有时考虑定义自定义Exception是有意义的。在您的情况下,可能是
class GraphError(Exception):
pass
raise GraphError("Node foo - rank limit exceeded")
要么
class LinkError(Exception):
message = "Node {node} - rank limit exceeded"
def __init__(self, node):
super(LinkError, self).__init__(
self.message.format(
node=node,
)
)
self.node = node
raise LinkError('foo')
关于python-3.x - 每种错误类型何时适用于Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61501941/