python如何抛出typeerror异常_Python:我如何知道方法调用可能抛出哪些异常

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(and don't tell me to read the documentation. 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 :)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值