python代码块怎么表示_如何在python中的一个块中写多个try语句?

1586010002-jmsa.png

I want to do:

try:

do()

except:

do2()

except:

do3()

except:

do4()

If do() fails, execute do2(), if do2() fails too, exceute do3() and so on.

best Regards

解决方案

I'd write a quick wrapper function first() for this.

usage: value = first([f1, f2, f3, ..., fn], default='All failed')

#!/usr/bin/env

def first(flist, default=None):

""" Try each function in `flist` until one does not throw an exception, and

return the return value of that function. If all functions throw exceptions,

return `default`

Args:

flist - list of functions to try

default - value to return if all functions fail

Returns:

return value of first function that does not throw exception, or

`default` if all throw exceptions.

TODO: Also accept a list of (f, (exceptions)) tuples, where f is the

function as above and (exceptions) is a tuple of exceptions that f should

expect. This allows you to still re-raise unexpected exceptions.

"""

for f in flist:

try:

return f()

except:

continue

else:

return default

# Testing.

def f():

raise TypeError

def g():

raise IndexError

def h():

return 1

# We skip two exception-throwing functions and return value of the last.

assert first([f, g, h]) == 1

assert first([f, g, f], default='monty') == 'monty'

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值