簡體   English   中英

如何打印 function 中出現的錯誤?

[英]How do I print an error raised inside a function?

我正在編寫一個可能會引發未知錯誤的代碼,我想打印這些錯誤以預測它們,但是如果我運行下面的示例,則沒有打印任何內容,有人可以向我解釋為什么會這樣嗎? 謝謝!

    def example():
        raise ConnectionError

    try:
        example()
    except Exception as e:
        print(e)

正如評論中所寫,您需要在引發錯誤時傳遞一條消息。

您還可以使用回溯庫來幫助您創建和顯示完整的回溯,如下所示:

import traceback

def example():
    raise ConnectionError("This is an alarm")

try:
    example()
except Exception:
    print(traceback.format_exc())

結果:

Traceback (most recent call last):
  File "c:\Users\xx\OneDrive\BACKUP\Python\testing_free.py", line 7, in <module>
    example()
  File "c:\Users\xx\OneDrive\BACKUP\Python\testing_free.py", line 4, in example
    raise ConnectionError("This is an alarm")
ConnectionError: This is an alarm

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM