Python从异常中获取错误代码

Pyt*_*421 7 python exception try-except

在 python 中,我有处理异常并打印错误代码和消息的代码。

try:
    somecode() #raises NameError
except Exception as e:
    print('Error! Code: {c}, Message, {m}'.format(c = e.code, m = str(e))
Run Code Online (Sandbox Code Playgroud)

但是,e.code这不是获取错误名称 (NameError) 的正确方法,我找不到答案。我如何获得错误代码?

小智 8

这对我有用。

  except Exception as e:
    errnum = e.args[0]
Run Code Online (Sandbox Code Playgroud)


小智 -3

尝试这个:

try:
    somecode() #raises NameError
except Exception as e:
    print('Error! Code: {c}, Message, {m}'.format(c = type(e).__name__, m = str(e)))
Run Code Online (Sandbox Code Playgroud)

阅读本文以获得更详细的解释。

  • 这不会打印错误代码,只打印异常的名称“NameError”和异常的消息 (5认同)
  • Mods:这不应被标记为正确答案,因为它没有回答问题。 (3认同)