Python中處理unchecked未捕獲異常執行個體_python

來源:互聯網
上載者:User

Talk Is Cheap

和Java一樣,python也提供了對於checked exception和unchecked exception. 對於checked exception,我們通常使用try except可以顯示解決,對於unchecked 異常,其實也是提供回調或者是鉤子來協助我們處理的,我們可以在鉤子裡面記錄崩潰棧追蹤或者發送崩潰資料.

下面代碼可以實現python unchecked exception回調,並輸出日誌資訊.

Show Me The Code

複製代碼 代碼如下:

#!/usr/bin/env python
# coding=utf-8
import os, sys
import logging
logger = logging.getLogger(__name__)
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return
    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

sys.excepthook = handle_exception
if __name__ == "__main__":
    raise RuntimeError("Test unhandled Exception")

相關解釋

1.上述忽略處理終端下鍵盤按Ctrl + C 終止異常.
2.上述使用python的日誌管理模組輸出格式化的異常資訊.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.