有没有办法找出哪个Python方法可以引发哪个异常或错误

no0*_*by5 2 python methods exception function

有没有办法找出哪个Python方法可以引发哪个异常或错误?我在官方Python文档中没有找到太多相关内容.

Ray*_*ger 6

一般来说,答案是否定的.一些例外情况已记录在案,但大多数情况只是遵循可以学习的一般模式. 首先检查SyntaxError,并引发语法无效的代码. 当变量未定义(尚未分配或拼写错误)时,会出现NameError. 针对错误数量的参数或不匹配的数据类型引发TypeError. ValueError意味着类型是正确的,但该值对函数没有意义(即,对math.sqrt()的负输入.如果值是序列查找中的索引,则引发IndexError.如果值是键对于映射查找,KeyError异常升高.另一种常见的例外是AttributeError的遗漏属性. IO错误是失败的I/O,而且OSERROR的操作系统错误.

除了学习常见模式之外,通常很容易运行一个函数并查看它在给定环境中引发的异常.

通常,函数不能知道或记录所有可能的错误,因为输入可以引发它们自己的异常.考虑这个功能:

def f(a, b):
    return a + b
Run Code Online (Sandbox Code Playgroud)

如果参数的数量错误或者a不支持该方法,它可能引发TypeError.但是,基础数据可能会引发不同的异常:__add__

>>> f(10)

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    f(10)
TypeError: f() takes exactly 2 arguments (1 given)
>>> f(10, 20)
30
>>> f('hello', 'world')
'helloworld'
>>> f(10, 'world')

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    f(10, 'world')
  File "<pyshell#2>", line 2, in f
    return a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> class A:
    def __init__(self, x):
        self.x = x
    def __add__(self, other):
        raise RuntimeError(other)

>>> f(A(5), A(7))

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    f(A(5), A(7))
  File "<pyshell#2>", line 2, in f
    return a + b
  File "<pyshell#12>", line 5, in __add__
    raise RuntimeError(other)
RuntimeError: <__main__.A instance at 0x103ce2ab8>
Run Code Online (Sandbox Code Playgroud)