python 3 try-except all with error [duplicate]

萝らか妹 提交于 2019-12-03 04:06:40

问题


Is it possible to do a try-except catch all that still shows the error without catching every possible exception? I have a case where exceptions will happen once a day every few days in a script running 24/7. I can't let the script die but they also don't matter since it retries regardless as long as I try except everything. So while I track down any last rare exceptions I want to log those to a file for future debugging.

example:

try:
    print(555)
except:
    print("type error: "+ str(the_error))

Any way to replace the_error with a stack trace or something similar?


回答1:


Yes you can catch all errors like so:

try:
    print(555)
except Exception as e:
    print("type error: " + str(e))

For the stack trace I usually use the traceback module:

import traceback

try:
    print(555)
except Exception as e:
    print("type error: " + str(e))
    print(traceback.format_exc())



回答2:


You can do:

   try:
       print(555)
   except Exception as err:
      print("Erro {}".format(err))

Or use raise

Docs are always your friend

Tip: Avoid use "except:"

Use something more descriptive like

...
except (ValueError, KeyError):

Unless your code is very well tested, you can't figure out every error.



来源:https://stackoverflow.com/questions/47103712/python-3-try-except-all-with-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!