我是Python的新手,这里是我正在看的一些代码:
try:
connection = getConnection(database)
cursor = connection.cursor()
cursor.execute("some query")
except:
log.error("Problem.")
raise
finally:
cursor.close()
connection.close()
Run Code Online (Sandbox Code Playgroud)
这是否正确清理?在我写的其他语言中,我习惯做这样的事情:
connection = None
cursor = None
try:
connection = getConnection(database)
cursor = connection.cursor()
cursor.execute("some query")
except:
log.error("Problem.")
raise
finally:
if cursor is not None:
cursor.close()
if connection is not None:
connection.close()
Run Code Online (Sandbox Code Playgroud) 我有一些像这样的python代码:
try:
bob = bob_module.Bob('alpha')
except Exception as e:
print 'Alpha mode failed for bob: ' + str(e) + ').'
try:
if bob:
bob.add('Beta')
else:
bob = bob_module.Bob('Beta')
except Exception as e:
print 'Beta mode failed for bob: ' + str(e) + ').'
Run Code Online (Sandbox Code Playgroud)
当此代码运行Alpha模式失败时,出于可理解的原因(与alpha服务器的交互失败).然而beta模式失败的原因是"名称'bob'未定义".
当然如果bob没有定义name 然后if bob等于false,我们将进入else子句并运行Bob构造函数将结果赋给变量bob?
我现在无法对此进行调试,因为导致Alpha模式失败的错误是暂时的,现在已经消失了,但我想了解这有两个原因:智力好奇,以及在alpha模式再次失败的情况下使我的代码健壮.