python-3.x - 每种错误类型何时适用于Python?

标签 python-3.x error-handling

如何判断要使用的错误类型(例如TypeErrorValueError)?

我知道我可以选择,但是根据上下文,某些选项比其他选项更相关吗?

示例:由于节点等级限制而无法在图形上添加边(我希望它是一个错误,而不仅仅是 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/

相关文章:

django - Django Unittest遇到错误

python - 使用 Telnet.write() 时出现类型错误

php - AWS Cache上的Codeigniter和错误日志/显示或调试未显示

python - 如何在 Django 中引发 410 错误

php - 错误: Strict Standards: Only variables should be passed by reference? [duplicate]

python - 如何在Python列表中使用计数器和zip函数?

python-3.x - 用于两步 ssh 隧道的 Jupyter notebook SSH 隧道

python - Pandas :合并(内部连接)数据框的行数比原来的多

python - 使用 Python 3 提取 XML 元素和属性数据

php - 有什么方法可以使PHP在未设置/ undefined variable 和数组索引等中止?