Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 异常中的异常处理_Python 3.x_Exception_Error Handling_Try Catch - Fatal编程技术网

Python 3.x 异常中的异常处理

Python 3.x 异常中的异常处理,python-3.x,exception,error-handling,try-catch,Python 3.x,Exception,Error Handling,Try Catch,所以我有以下两个不同的try-except块,我不理解输出,我相信这是因为except块中的异常。尽管我发现了一些标题类似的问题,但它们并没有帮助我回答我的问题 第一个街区: try: try: raise IndexError x = 5/0 except ArithmeticError: print("1") print("2") except IndexError: print("3")

所以我有以下两个不同的try-except块,我不理解输出,我相信这是因为except块中的异常。尽管我发现了一些标题类似的问题,但它们并没有帮助我回答我的问题

第一个街区:

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
既然我们抓到了索引器,为什么最后一个异常是5? 我知道raise索引器被第二个捕获,除了我们得到3,因为finally总是被执行,所以4也被打印出来

第二个相关问题:

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
raise索引器如何不执行print3语句?既然在第一个示例中没有得到5输出,为什么这次我们要得到5输出?

except将捕获在try中抛出的异常,但不会捕获除块之外的其他同级中抛出的异常。对于使用多个同级块(除外)的任何给定尝试,其中一个除外块将处理异常

在第一个示例中,未打印5,因为外部try中的代码不会引发异常。内部try中的异常被抛出,并由该级别的一个except块处理


在第二个示例中,没有打印3,因为try块中的代码没有抛出索引器。它抛出一个算术错误,该错误被相应的except块捕获。然后,该块还会抛出一个异常,该异常存在于整个try/except结构中,并被更高的except块捕获。

哦,我明白了,我今天应该暂停它。第一个例子完全清楚。但是非常感谢对第二个例子的解释。说清楚了!