如何在Python中在一個except塊中引發異常並在後面的except塊中捕獲它?
try塊中只調用一個except子句。如果你希望異常在更高層級被捕獲,那麼你需要使用巢狀try塊。
我們編寫類似這樣的2個try...except塊
try: try: 1/0 except ArithmeticError as e: if str(e) == "Zero division": print ("thumbs up") else: raise except Exception as err: print ("thumbs down") raise err
我們得到以下輸出
thumbs down Traceback (most recent call last): File "C:/Users/TutorialsPoint1/~.py", line 11, in <module> raise err File "C:/Users/TutorialsPoint1/~.py", line 3, in <module> 1/0 ZeroDivisionError: division by zero
按照python教程,對於一個try語句,有一個且只有一個被捕獲或被捕獲的異常。
廣告