簡體   English   中英

如何在 python 中捕獲異常消息?

[英]How to catch an exception message in python?

我想要某種形式的東西

try:
  # code
except *, error_message:
  print(error_message)

即我想要一個通用的 except 塊來捕獲所有類型的異常並打印錯誤消息。 例如。 “ZeroDivisionError:除以零”。 python 有可能嗎?

如果我執行以下操作,我可以捕獲所有異常,但不會收到錯誤消息。

try:
  # code
except:
  print("Exception occurred")

嘗試這個:

except Exception as e:
    print(str(e))

這將允許您檢索從Exception庫 class 派生的任何異常的消息:

try:
    raise Exception('An error has occurred.')
except Exception as ex:
    print(str(ex))

暫無
暫無

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

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