Python try 块中的所有内容
我正在用Python编写一个大型批处理类型的脚本,无论是否发生异常,最后都需要进行一些清理。为此,我只需将主程序放在 try 块中,并将清理放在 finally 块中。
这似乎运行良好,但我的问题是如何打印可能发生的任何异常。目前它只是忽略它们并跳转到finally 块。
I am writing a large batch-type script in Python, and need to do some cleanup in the end, regardless of whether an exception occurred. To do this I'm simply putting the main program in a try block and the cleanup in a finally block.
This seems to work well, but my question is how to print any exceptions that might occur. Currently it just ignores them and jumps to the finally block.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够使用没有异常处理程序的
try
/finally
块。它不会捕获异常或抑制回溯,只是确保无论是否存在异常都会运行清理代码。这就是finally
的全部要点。这是一个例子:
You should just be able to use a
try
/finally
block with no exception handler. It won't catch the exception or suppress the traceback, just ensure your cleanup code is run whether or not there is an exception. That's the entire point offinally
.Here's an example:
你可以使用回溯。
像这样的东西:
you can use traceback.
something like: