如何尝试平面样式的几种方法?

如果我想尝试很多方法来避免一些错误,我可以写:

try:

    try:
        trial_1()
    except some_error:
        try:
            trial_2()
        except some_error:
            try:
                trial_3()
            ...
    print "finally pass"

except some_error:
    print "still fail"

但是有太多的试验,所以太多的巢,如何以平面样式写它?

解决方法:

你可以这样做:

def trial1 (): 42 / 0
def trial2 (): [] [42]
def trial3 (): 'yoohoo!'
def trial4 (): 'here be dragons'

for t in [trial1, trial2, trial3, trial4]:
    print ('Trying {}.'.format (t.__name__) )
    try:
        t ()
        print ('Success')
        break
    except Exception as ex:
        print ('Failed due to {}'.format (ex) )
else:
    print ('Epic fail!')

输出是:

Trying trial1.
Failed due to division by zero
Trying trial2.
Failed due to list index out of range
Trying trial3.
Success
上一篇:CentOS7 kubeadm 搭建 K8S 1.20.5 (containerd 容器运行时)


下一篇:Kubernetes 用kubeadm安装kubernetes_v1.18.x