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

时间:2020-06-05 16:37:48

标签: python exception try-catch

我想要某种形式的东西

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

即我想拥有一个通用的除外块,该块可以捕获所有类型的异常并显示错误消息。例如。 “ ZeroDivisionError:被零除”。在python中可以吗?

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

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

2 个答案:

答案 0 :(得分:1)

尝试一下:

Type '(message: string) => string | boolean | null | undefined' is not assignable to type '((message?: any) => void) & ((message?: any) => void) & ((message?: string | undefined, _default?: string | undefined) => string | null) & ((message?: string | undefined, _default?: string | undefined) => string | null) & ((message?: string | undefined) => boolean) & ((message?: string | undefined) => boolean)'.
  Type '(message: string) => string | boolean | null | undefined' is not assignable to type '(message?: string | undefined, _default?: string | undefined) => string | null'.
    Type 'string | boolean | null | undefined' is not assignable to type 'string | null'.
      Type 'undefined' is not assignable to type 'string | null'.(2322)

答案 1 :(得分:1)

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

try:
    raise Exception('An error has occurred.')
except Exception as ex:
    print(ex.message)
相关问题