0

像这样的东西

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] 引发后,并且 [except ZeroDivisionError] 捕获错误,然后返回 [print "hello world"] 行,然后继续...

4

6 回答 6

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

于 2013-08-26T11:45:17.207 回答
3

不,当引发异常时,它总是会转到捕获它的块。如果您想返回到导致异常的那一行之后,您应该立即处理该异常,然后将该行放在处理该异常的代码下方。

于 2013-08-26T11:43:58.807 回答
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..."
于 2013-08-26T11:49:03.563 回答
1

您可以将打印行放在try... except语句之后,并为第二个 except 使用第二个try ... except语句。

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..."

无论如何,在第二种例外情况下,如果您只想停止程序,则不应捕获异常。

于 2013-08-26T11:43:55.340 回答
1

你不能不特别提到你想在哪里捕获错误以及什么不需要被捕获。

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

try:
    1/0
except ZeroDivisionError:
    print "error"
finally:
    print "hello world"
    print "every thing seems fine..."
于 2013-08-26T11:45:18.897 回答
0

正如其他答案所示,此处该try/except子句的正确用法是使用else或两者兼而有之。finally

但是,您也可以重构您的代码,以便尝试的每一步都是自己的函数,然后使用循环将它们很好地组合在一起。

例子:

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...
于 2013-08-26T11:54:53.577 回答