我在 Python2.7.9
中为一个小项目制作了一个 map 编辑器,我正在寻找在出现某些未处理的异常时保留我编辑的数据的方法。我的编辑器已经有了保存数据的方法,我目前的解决方案是将主循环包裹在 try..finally
block 中,类似于此示例:
import os, datetime #..and others.
if __name__ == '__main__':
DataMgr = DataManager() # initializes the editor.
save_note = None
try:
MainLoop() # unsurprisingly, this calls the main loop.
except Exception as e: # I am of the impression this will catch every type of exception.
save_note = "Exception dump: %s : %s." % (type(e).__name__, e) # A memo appended to the comments in the save file.
finally:
exception_fp = DataMgr.cwd + "dump_%s.kmap" % str(datetime.datetime.now())
DataMgr.saveFile(exception_fp, memo = save_note) # saves out to a dump file using a familiar method with a note outlining what happened.
这似乎是确保无论发生什么情况,都会尝试保留编辑器当前状态的最佳方式(在 saveFile()
能够做到这一点的范围内)如果它应该崩溃。但我想知道将我的整个主循环封装在 try
block 中是否实际上是安全、高效和良好的形式。是吗?有没有风险或问题?有没有更好或更传统的方法?
最佳答案
当您无论如何都需要发生某些事情时,将主循环包装在try...finally
block 中是可接受的模式。在某些情况下,它会记录并继续,而在其他情况下,它会保存所有可能的内容并退出。
所以你的代码没问题。
关于python - 将整个主循环包装在 try..finally block 中是否合理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29860113/