python 3 try-except all with error
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47103712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python 3 try-except all with error
提问by Ryan Mills
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.
是否可以在不捕获所有可能的异常的情况下执行 try-except 捕获所有仍显示错误的操作?我有一个案例,在 24/7 运行的脚本中,每隔几天每天都会发生一次异常。我不能让脚本死掉,但它们也无关紧要,因为只要我尝试除所有内容,它都会重试。因此,当我追踪任何最后的罕见异常时,我想将它们记录到文件中以备将来调试。
example:
例子:
try:
print(555)
except:
print("type error: "+ str(the_error))
Any way to replace the_error
with a stack trace or something similar?
有什么办法可以the_error
用堆栈跟踪或类似的东西替换吗?
回答by Cyzanfar
Yes you can catch all errorslike so:
是的,您可以像这样捕获所有错误:
try:
print(555)
except Exception as e:
print("type error: " + str(e))
For the stack trace I usually use the tracebackmodule:
对于堆栈跟踪,我通常使用回溯模块:
import traceback
try:
print(555)
except Exception as e:
print("type error: " + str(e))
print(traceback.format_exc())
回答by Joao Vitorino
You can do:
你可以做:
try:
print(555)
except Exception as err:
print("Erro {}".format(err))
Or use raise
或使用 raise
Docsare 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.
除非您的代码经过很好的测试,否则您无法找出每个错误。