3 python
功能代码:
# Connect to the DB
try:
dbi = MySQLdb.connect(host='localhost', \
user='user', \
passwd='pass', \
db='dbname', \
port=3309)
print "Connected to DB ..."
except MySQLdb.Error, e:
apiErr = 2
apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
return
# To prevent try..finally bug in python2.4,
# one has to nest the "try: except:" part.
try:
try:
sql = dbi.cursor()
sql.execute("""
SELECT *
FROM table
WHERE idClient = %s
""", (key, ))
access = sql.fetchall()
# [some more code here]
except MySQLdb.Error, e:
apiErr = 2
apiErrMsg = "Error %d: %s" % (e.args[0], e.args[1])
return
finally:
sql.close()
dbi.close()
Run Code Online (Sandbox Code Playgroud)
我理解在尝试..除了..最后,finally块将始终执行.在上面的代码中,如果第一个try块中存在异常,我不希望第二个try块中的finally执行.我究竟做错了什么?
(注意:使用python 2.4)
澄清:我不知道MySQLdb是否在发生错误时自动关闭连接.我在上面的代码中面临的问题是,当建立连接时出错(代码的第一个try块)时,在finally块中调用dbi.close()会引发"AttributeError:'NoneType'对象没有属性'close'"参考dbi ...
解决方案:这可以按预期工作 -
# define at the start
dbi = None
sql = None
Run Code Online (Sandbox Code Playgroud)
在finally块中,
if sql is not None:
sql.close()
if dbi is not None:
dbi.close()
Run Code Online (Sandbox Code Playgroud)
感谢那些回复的人.我从大家那里学到了一些新东西.(我会在下次更清楚地说出我的问题:).
用else:而不是finally:.请参阅文档的异常处理部分:
该
try ... except语句有一个可选的else子句,如果存在,则必须遵循所有except子句.如果try子句不引发异常,则必须执行的代码很有用.
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
Run Code Online (Sandbox Code Playgroud)
..基本上:
try:
[code that might error]
except IOError:
[This code is only ran when IOError is raised]
else:
[This code is only ran when NO exception is raised]
finally:
[This code is always run, both if an exception is raised or not]
Run Code Online (Sandbox Code Playgroud)
我认为在这种情况下你确实想要最终使用,因为你想要关闭这些连接.
我不同意你应该在同一个方法中有两个try块的想法.
我认为设计中的缺陷是获取连接并以相同的方法执行查询.我建议将两者分开.服务类或方法知道工作单元.它应该获取连接,将其传递给另一个执行查询的类,并在完成后关闭连接.这样,查询方法可以抛出它遇到的任何异常,并将清理留给负责连接的类或方法.