python 3尝试 - 除了所有错误

Rya*_*lls 40 python python-3.x try-except

是否有可能尝试 - 除了捕获所有仍然显示错误而不捕获每个可能的异常?我有一个案例,在每天24小时运行的脚本中,每隔几天就会发生一次异常.我不能让脚本死掉,但它们也没关系,因为只要我尝试除了一切,它都会重试.因此,当我追踪任何最后罕见的异常时,我想将它们记录到文件中以供将来调试.

例:

try:
    print(555)
except:
    print("type error: "+ str(the_error))
Run Code Online (Sandbox Code Playgroud)

the_error有没有什么方法可以替换堆栈跟踪或类似的东西?

Cyz*_*far 89

是的,您可以捕获所有错误:

try:
    print(555)
except Exception as e:
    print("type error: " + str(e))
Run Code Online (Sandbox Code Playgroud)

对于堆栈跟踪,我通常使用traceback模块:

import traceback

try:
    print(555)
except Exception as e:
    print("type error: " + str(e))
    print(traceback.format_exc())
Run Code Online (Sandbox Code Playgroud)


Joa*_*ino 11

你可以做:

   try:
       print(555)
   except Exception as err:
      print("Erro {}".format(err))
Run Code Online (Sandbox Code Playgroud)

或使用 raise

文件永远是您的朋友

提示:避免使用“除外:”

使用更具描述性的内容,例如

...
except (ValueError, KeyError):
Run Code Online (Sandbox Code Playgroud)

除非您的代码经过了很好的测试,否则您将无法找出所有错误。