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 :)
这篇关于我如何知道方法调用可能引发哪些异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我如何知道方法调用可能引发哪些异常?
基础教程推荐
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
