如何在Python中捕获异常消息?

Ees*_*aan 8 python exception try-catch

我想要某种形式的东西

try:
  # code
except *, error_message:
  print(error_message)
Run Code Online (Sandbox Code Playgroud)

即我想要一个通用的 except 块来捕获所有类型的异常并打印错误消息。例如。“ZeroDivisionError:除以零”。在Python中可以吗?

如果我执行以下操作,我可以捕获所有异常,但不会收到错误消息。

try:
  # code
except:
  print("Exception occurred")
Run Code Online (Sandbox Code Playgroud)

Jak*_*kob 14

尝试这个:

except Exception as e:
    print(str(e))
Run Code Online (Sandbox Code Playgroud)


Ósc*_*pez 5

这将允许您检索从基类派生的任何异常的消息Exception

try:
    raise Exception('An error has occurred.')
except Exception as ex:
    print(str(ex))
Run Code Online (Sandbox Code Playgroud)