catch exception in outer try/except
在下面的代码中,
1 2 3 4 5 6 7 8 9 10 | def func(): try: try: # No changes to be made here x = 2/0 # No changes to be made here except ZeroDivisionError: # No changes to be made here print"Division by zero is not possible" # No changes to be made here except: raise Exception("Exception caught") func() |
有没有办法让外部try/except块在不更改内部try/except的情况下引发异常?
您可以这样链接代码异常:
1 2 3 4 5 6 7 | def func(): try: x = 2/0 except ZeroDivisionError: # specific exception print"Division by zero is not possible" except Exception: # catch all exception raise Exception("Exception caught") |
听起来您真正想做的是捕获另一个函数引发的异常。要做到这一点,您需要从函数中引发一个异常(即,在示例中,内部try/except)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def func1(): try: x = 2/0 except ZeroDivisionError: print"Division by zero is not possible" raise def func2(): try: func1() except ZeroDivisionError: print"Exception caught" func2() # Division by zero is not possible # Exception caught |
注意,我做了两个关键的改变。1)我在内部函数中提出了错误。2)我在第二个函数中捕获了特定的异常。