How can I know which exceptions might be thrown from a method call?(我如何知道方法调用可能引发哪些异常?)
问题描述
有没有办法知道(在编码时)执行 python 代码时会出现哪些异常?
Is there a way knowing (at coding time) which exceptions to expect when executing python code?
我最终会在 90% 的情况下捕获基本异常类,因为我不知道可能会抛出哪种异常类型(阅读文档并不总是有帮助,因为很多时候异常可以从深层传播.而且很多时候文档没有更新或不正确).
I end up catching the base Exception class 90% of the time since I don't know which exception type might be thrown (reading the documentation doesn't always help, since many times an exception can be propagated from the deep. And many times the documentation is not updated or correct).
是否有某种工具可以检查这一点(例如通过阅读 Python 代码和库)?
Is there some kind of tool to check this (like by reading the Python code and libs)?
推荐答案
我猜一个解决方案可能只是因为缺少静态类型规则而不够精确.
I guess a solution could be only imprecise because of lack of static typing rules.
我不知道有什么工具可以检查异常,但您可以根据自己的需要提出自己的工具(这是玩一些静态分析的好机会).
I'm not aware of some tool that checks exceptions, but you could come up with your own tool matching your needs (a good chance to play a little with static analysis).
作为第一次尝试,您可以编写一个构建 AST 的函数,查找所有 Raise
节点,然后尝试找出引发异常的常见模式(例如直接调用构造函数)
As a first attempt, you could write a function that builds an AST, finds all Raise
nodes, and then tries to figure out common patterns of raising exceptions (e. g. calling a constructor directly)
设x
为以下程序:
x = '''
if f(x):
raise IOError(errno.ENOENT, 'not found')
else:
e = g(x)
raise e
'''
使用 compiler
包构建 AST:
Build the AST using the compiler
package:
tree = compiler.parse(x)
然后定义一个Raise
访问者类:
Then define a Raise
visitor class:
class RaiseVisitor(object):
def __init__(self):
self.nodes = []
def visitRaise(self, n):
self.nodes.append(n)
并走AST收集Raise
节点:
v = RaiseVisitor()
compiler.walk(tree, v)
>>> print v.nodes
[
Raise(
CallFunc(
Name('IOError'),
[Getattr(Name('errno'), 'ENOENT'), Const('not found')],
None, None),
None, None),
Raise(Name('e'), None, None),
]
您可以继续使用编译器符号表解析符号,分析数据依赖关系等.或者您可以推断,CallFunc(Name('IOError'), ...)
肯定应该意思是提高IOError
",这对于快速的实际结果来说是完全可以的:)
You may continue by resolving symbols using compiler symbol tables, analyzing data dependencies, etc. Or you may just deduce, that CallFunc(Name('IOError'), ...)
"should definitely mean raising IOError
", which is quite OK for quick practical results :)
这篇关于我如何知道方法调用可能引发哪些异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我如何知道方法调用可能引发哪些异常?


基础教程推荐
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01