简体   繁体   English

异常中的异常处理

[英]Exception handling within exception

So I have following two different try-except blocks, where I do not understand the output and I believe it is because of Exceptions within except blocks.所以我有以下两个不同的 try-except 块,我不理解输出,我相信这是因为 except 块内的异常。 Even though I found a few questions with a similar title, they did not help me answering my question.尽管我发现了一些标题相似的问题,但它们并没有帮助我回答我的问题。

First block:第一个区块:

try:
    try:
        raise IndexError
        x = 5/0
    except ArithmeticError:
        print("1")
        print("2")
    except IndexError:
        print("3")
    finally:
        print("4")
except:
    print("5")                #Output: 3 4

Since we caught the IndexError, why does the last exception 5 ?既然我们捕获了 IndexError,为什么最后一个异常5呢? ( I do understand that the raise IndexError is caught by the second except and we get the 3 , and since finally is always executed , 4 is printed out aswell ). 我确实理解raise IndexError被第二个 except 捕获,我们得到3并且因为 finally 总是被执行4也被打印出来)。

Second (related) Question:第二个(相关)问题:

try:
    try:
        x = 5/0
    except ArithmeticError:
        print("1")
        raise IndexError            # this is different this time!
        print("2")
    except IndexError:
        print("3")
    finally:
        print("4")
except:
    print("5")                      #Output: 1 4 5

How is it, that the raise IndexError does not execute the print("3") statement?怎么, raise IndexError不执行print("3")语句? And why do we get the 5 output this time, since we did not get it in the first example?为什么我们这次得到 5 输出,因为我们在第一个例子中没有得到它?

except will catch exceptions thrown in the try , but not in other sibling except blocks. except会捕获在try抛出的异常,但不会exceptexcept其他兄弟中捕获。 For any given try with multiple sibling except blocks, one of those except blocks will handle the exception.对于任何给定try与多个兄弟except块,其中的一个except块将处理这个异常。

In your first example 5 is not printed because the code within the outer try does not throw an exception.在您的第一个示例中5未打印,因为外部try中的代码不会引发异常。 An exception in the inner try is thrown, and is handled by one of the except blocks at that level.内部try中的异常被抛出,并由该级别的except块之一处理。

In your second example 3 is not printed because the code in the try block does not throw an IndexError .在您的第二个示例中3未打印,因为try块中的代码不会引发IndexError It throws an ArithmeticError , which is caught by the corresponding except block.它抛出一个ArithmeticError ,它被相应的except块捕获。 That block then also throws an exception, which exist the entire try/except structure and gets caught by a higher except block.然后块也会抛出一个异常,该异常存在于整个try/except结构中,并被更高的except块捕获。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM