Python 中異常嵌套


在Python中,異常也可以嵌套,當內層代碼出現異常時,指定異常類型與實際類型不符時,則向外傳,如果與外面的指定類型符合,則異常被處理,直至最外層,運用默認處理方法進行處理,即停止程序,並拋出異常信息。如下代碼:

try:
    try:
        raise IndexError
    except TypeError:
        print('get handled')
except SyntaxError:
    print('ok')

運行程序:

Traceback (most recent call last):
  File "<pyshell#47>", line 3, in <module>
    raise IndexError
IndexError

再看另一個被外層try-except捕獲的例子:

try:
    try:
        1/0
    finally:
        print('finally')
except:
    print('ok')

運行:

finally
ok

這里值得注意的是except:可以捕獲所有的異常,但實際上這樣做也有缺點,即有時候會包住預定的異常。

另外,需要提到的是raise A from B,將一個異常與另一個異常關聯起來,如果from后面的B沒有被外層捕獲,那么A,B異常都將拋出,例如:

try:
    1/0
except Exception as E:
    raise TypeError('bad') from E

運行:

Traceback (most recent call last):
  File "<pyshell#4>", line 2, in <module>
    1/0
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<pyshell#4>", line 4, in <module>
    raise TypeError('bad') from E
TypeError: bad

相反,如果外層捕獲了B:

try:
    try:
        1/0
    except Exception as E:
        raise TypeError from E
except TypeError:
    print('no'

運行:

no

最后,再看看try-finally在嵌套中的表現。

 try:
    try:
        1/0
    finally:
        print('finally')
except:
    print('ok')

運行:

finally
ok

不管有沒有異常發生,或者其是否被處理,finally的代碼都要執行,如果異常被處理,則停止,如果沒有被處理,向外走,直至最終沒處理,采用默認方法處理,上例中,異常在最外層被處理。

try:
    try:
        1/0
    except Exception as E:
        print('happens')
    finally:
        print('finally')
except E:
    print('get handled')

運行:

happens
finally

異常在內部被處理,不再向外傳播。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM