python可以忽略错误并返回到凸起行旁边的行并继续

时间:2013-08-26 11:40:56

标签: python

就像那样

try: 
    1/0
    print "hello world"
    print "every thing seems fine..."

except ZeroDivisionError: 
    print "It is not a critical error, go to next..."
    SomeWayAllowMeToExeutePrintHelloWorld_TheLineNextToTheRaisedLine()

except: 
    print "I have no idea, just stop work..."

[1/0]引发后,[除ZeroDivisionError]捕获错误,然后返回[print“hello world”]行,继续......

6 个答案:

答案 0 :(得分:4)

你不能,也没有理由你想要:

try: 
    1/0
except ZeroDivisionError:
    print "It is not a critical error, go to next..."

print "hello world"
print "every thing seems fine..."

考虑以下代码:

try: 
    important_res = f(1/0)
    send_important_message(important_res)
except ZeroDivisionError: 
    print "It is not a critical error, go to next..."
    SomeWayAllowMeToExeutePrintHelloWorld_TheLineNextToTheRaisedLine()

如果您允许继续执行,您如何选择要传递给f的值?

答案 1 :(得分:3)

没有。当引发异常时,它总是进入捕获它的块。如果要返回导致异常的行之后的行,则应立即处理异常,然后在处理异常的代码下面放置该行。

答案 2 :(得分:2)

没有。实现您想要的方法是使用两个try语句:

try:
    try: 
        1/0
    except ZeroDivisionError: 
        print "It is not a critical error, go to next..."

    print "hello world"
    print "every thing seems fine..."
except: 
    print "I have no idea, just stop work..."

答案 3 :(得分:1)

您可以将打印行放在 try ... except 语句之后,并对第二个使用第二个 try ... except 语句,但< / em>的

try:
    try: 
        1/0

    except ZeroDivisionError: 
        print "It is not a critical error, go to next..."

except: 
    print "I have no idea, just stop work..."

print "hello world"
print "every thing seems fine..."

通过,在第二个的情况下,如果你只想停止程序,你不应该捕获异常。

答案 4 :(得分:1)

你不能没有特别提到你想要捕捉错误的地方以及不需要捕获的内容。

执行上述操作后,您可以添加finally:代码块:

try:
    1/0
except ZeroDivisionError:
    print "error"
finally:
    print "hello world"
    print "every thing seems fine..."

答案 5 :(得分:0)

此处try/except子句的正确用法是使用elsefinally或两者,正如其他答案所示。

但是,你也可以重构你的代码,这样尝试的每一步都是它自己的功能,然后使用循环很好地把它们放在一起。

示例:

steps = [step1, step2, step3] # pointers to function/methods

for step in steps:
    try:
        step()
    except Exception as exc:
        # handle the exception

在你的代码上:

def step1():
    1/0

def step2():
    print "hello world"

def step3():
    print "every thing seems fine..."

steps = [step1, step2, step3]

for step in steps:
    try:
        step()
    except ZeroDivisionError:
        print "It is not a critical error, go to next..."
    except:
        print "I have no idea, just stop work..."

结果:

>>> 
It is not a critical error, go to next...
hello world
every thing seems fine...