python最大递归次数_超过处理最大递归深度

最大递归深度错误只是另一个异常;您可以捕获^{} exception(Python 3.5或更高版本):try:

solveMaze(maze)

except RecursionError as re:

print('Sorry but this maze solver was not able to finish '

'analyzing the maze: {}'.format(re.args[0]))

我已经合并了附加到运行时异常的错误消息;对于递归错误是maximum recursion depth exceeded。

如果需要支持早于3.5的Python版本,可以捕获基类^{}。如果您担心捕获而不是递归深度错误的运行时错误,那么您可以内省.args[0]值:try:

solveMaze(maze)

except RuntimeError as re:

if re.args[0] != 'maximum recursion depth exceeded':

# different type of runtime error

raise

print('Sorry but this maze solver was not able to finish '

'analyzing the maze: {}'.format(re.args[0]))

选项演示:>>> def infinity(): return infinity()

...

>>> try:

... infinity()

... except RecursionError as re:

... print('Oopsie: {}'.format(re.args[0]))

...

Oopsie: maximum recursion depth exceeded

>>> def alter_dict_size():

... dct = {'foo': 'bar'}

... for key in dct:

... del dct['foo']

...

>>> try:

... alter_dict_size()

... except RuntimeError as re:

... print('Oopsie: {}'.format(re.args[0]))

...

Oopsie: dictionary changed size during iteration

>>> try:

... infinity()

... except RuntimeError as re:

... if re.args[0] != 'maximum recursion depth exceeded':

... raise

... print('Oopsie: {}'.format(re.args[0]))

...

Oopsie: maximum recursion depth exceeded

>>> try:

... alter_dict_size()

... except RuntimeError as re:

... if re.args[0] != 'maximum recursion depth exceeded':

... raise

... print('Oopsie: {}'.format(re.args[0]))

...

Traceback (most recent call last):

File "", line 2, in

File "", line 3, in alter_dict_size

RuntimeError: dictionary changed size during iteration

改变字典大小也会引发RuntimeError异常,但是测试生成的异常消息允许您区分。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值