让 x 成为以下程序:x = '''如果 f(x):引发 IOError(errno.ENOENT,'未找到')别的:e = g(x)提高e'''使用 compiler 包构建 AST:tree = compiler.parse(x)然后定义一个Raise访问者类:class RaiseVisitor(object):def __init__(self):self.nodes = []def visitRaise(self, n):self.nodes.append(n)并走AST收集Raise节点:v = RaiseVisitor()compiler.walk(tree, v)>>>打印 v.nodes[增加(调用函数(名称('IOError'),[Getattr(Name('errno'), 'ENOENT'), Const('not found')],无,无),无,无),提高(名称('e'),无,无),]您可以继续使用编译器符号表解析符号,分析数据依赖性等.或者您可以推断出,CallFunc(Name('IOError'), ...)肯定应该意味着提高 IOError",这对于快速的实际结果来说是可以的 :)Is there a way knowing (at coding time) which exceptions to expect when executing python code?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).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).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)Let x be the following program:x = '''if f(x): raise IOError(errno.ENOENT, 'not found')else: e = g(x) raise e'''Build the AST using the compiler package:tree = compiler.parse(x)Then define a Raise visitor class:class RaiseVisitor(object): def __init__(self): self.nodes = [] def visitRaise(self, n): self.nodes.append(n)And walk the AST collecting Raise nodes: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),]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 :) 这篇关于我如何知道方法调用可能会抛出哪些异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-19 19:26