【问题标题】:Is there a way to find out which Python method can raise which Exception or Error有没有办法找出哪个 Python 方法可以引发哪个异常或错误
【发布时间】:2017-09-24 12:07:42
【问题描述】:

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

【问题讨论】:

  • 几乎任何事情都可能引发异常,特别是如果你传递它无法处理的参数。
  • “哪个 Python 方法可以引发哪个异常或错误”是指哪个方法引发它,还是仅仅有能力引发它?
  • 我的意思是可能由特定方法引发的异常/错误。
  • 那么答案是否定的。

标签: python function exception methods


【解决方案1】:

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

除了学习常见模式之外,通常很容易只运行一个函数并查看它在给定情况下引发什么异常。

一般来说,函数无法知道或记录所有可能的错误,因为输入可能引发它们自己的异常。考虑这个函数:

def f(a, b):
    return a + b

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

>>> 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>

【讨论】:

    【解决方案2】:

    您可以使用__name__ 找到异常的名称,例如:

    try : 
        some_function()
    except Exception as ex : 
        print('function: {0}, exception: {1}'.format(some_function.__name__, type(ex).__name__))
    

    【讨论】:

      猜你喜欢
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 2021-05-30
      • 2020-03-30
      相关资源
      最近更新 更多