Python Cookbook(第3版)中文版:14.10 重新拋出被捕獲的異常

來源:互聯網
上載者:User

標籤:人工   AC   recent   執行   val   ali   ...   ISE   form   

14.10 重新拋出被捕獲的異常?問題?

你在一個 except 塊中捕獲了一個異常,現在想重新拋出它。

解決方案?

簡單的使用一個單獨的 rasie 語句即可,例如:

>>> def example():...     try:...             int(‘N/A‘)...     except ValueError:...             print("Didn‘t work")...             raise...>>> example()Didn‘t workTraceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 3, in exampleValueError: invalid literal for int() with base 10: ‘N/A‘>>>
討論?

這個問題通常是當你需要在捕獲異常後執行某個操作(比如記錄日誌、清理等),但是之後想將異常傳播下去。
一個很常見的用法是在捕獲所有異常的處理器中:

try:   ...except Exception as e:   # Process exception information in some way   ...   # Propagate the exception   raise

艾伯特(http://www.aibbt.com/)國內第一家人工智慧門戶

Python Cookbook(第3版)中文版:14.10 重新拋出被捕獲的異常

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.