简体   繁体   English

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

[英]Is there a way to find out which Python method can raise which Exception or Error

Is there a way to find out which Python method can raise which Exception or Error? 有没有办法找出哪个Python方法可以引发哪个异常或错误? I didn't find much about it in the official Python documentation. 我在官方Python文档中没有找到太多相关内容。

In general, the answer is no. 一般来说,答案是否定的。 Some of the exceptions are documented but most just follow a general pattern that can be learned. 一些例外情况已记录在案,但大多数情况只是遵循可以学习的一般模式。 SyntaxError is checked first and is raised for syntactically invalid code. 首先检查SyntaxError ,并引发语法无效的代码。 NameError arises when a variable is undefined (not assigned yet or misspelled). 当变量未定义(尚未分配或拼写错误)时,会出现NameError TypeError is raised for the wrong number of arguments or mismatched data types. 针对错误数量的参数或不匹配的数据类型引发TypeError ValueError means the type is correct and but the value doesn't make sense for the function (ie negative inputs to math.sqrt(). If the value is an index in a sequence lookup, IndexError is raised. If the value is a key for a mapping lookup, KeyError is raised. Another common exception is AttributeError for missing attributes. IOError is for failed I/O. And OSError for operating system errors. ValueError意味着类型是正确的,但该值对函数没有意义(即,对math.sqrt()的负输入。如果值是序列查找中的索引,则引发IndexError 。如果值是键对于映射查找,KeyError异常升高。另一种常见的例外是缺少的属性AttributeError错误 。IO错误是失败的I / O。而对于OSERROR操作系统错误。

Besides learning the common patterns, it is usually easy to just run a function and see what exception it raises in a given circumstance. 除了学习常见模式之外,通常很容易运行一个函数并查看它在给定环境中引发的异常。

In general a function cannot know or document all the possible errors, because the inputs can raise their own exceptions. 通常,函数不能知道或记录所有可能的错误,因为输入可以引发它们自己的异常。 Consider this function: 考虑这个功能:

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

It can raise TypeError if the number of arguments are wrong or if a doesn't support the __add__ method. 如果参数的数量错误或者a不支持__add__方法,它可能引发TypeError However, the underlying data can raise different exceptions: 但是,基础数据可能会引发不同的异常:

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

You can find the name of the exception with __name__ , example : 您可以使用__name__找到例外的名称,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:需要kwarg,哪个例外要加注? - Python: required kwarg, which exception to raise? 在Django / Python中,我如何找出调用my方法的方法? - In Django/Python, how can I find out which method called my method? 在此方法的python3中引发一个异常,该异常将使用默认值检查dictionary.get? - Raise an exception in python3 for this method which check dictionary.get with default value? 我应该为只能调用一次的函数引发python中的哪种标准异常 - What kind of the standard exception in python should I raise for a function which can only be invoked once 对于 Python 中的错误/非法参数组合,我应该引发哪个异常? - Which exception should I raise on bad/illegal argument combinations in Python? python如何重新引发已经捕获的异常? - python how to re-raise an exception which is already caught? 我应该针对REST API错误提出哪个异常? - Which exception should I raise for a REST API error? 哪个是处理ImportError的更好方法-引发错误或导入链? - Which is the better way to handle ImportError - Raise error or import chain? 在引发错误和记录错误之间,在Python中哪种更好的做法? - Between raise Error and logging the Error, which one is a better practice in Python? 这是引发异常的正确方法吗? (蟒蛇) - Is this the correct way to raise an Exception? (Python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM