在 try、catch、finally 语句中使用变量而不在外部声明它 [英] Using a variable in a try,catch,finally statement without declaring it outside

查看:31
本文介绍了在 try、catch、finally 语句中使用变量而不在外部声明它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Python 还很陌生,这是我正在查看的一些代码:

I'm pretty new to Python, here is some code I am looking at:

try:
    connection = getConnection(database)
    cursor = connection.cursor()
    cursor.execute("some query")
except:
    log.error("Problem.")
    raise
finally:
    cursor.close()
    connection.close()

是否正确清理?在我写过的其他语言中,我习惯于做这样的事情:

Is that being cleaned up properly? In other languages I have written in, I am used to doing something like this:

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()

推荐答案

Python 没有块作用域.try 块内定义的任何内容都可以在外部使用.

Python does not have block scope. Anything defined inside the try block will be available outside.

也就是说,您仍然会遇到问题:如果是 getConnection() 调用引发错误,cursor 将是未定义的,因此finally 块会出错.

That said, you would still have a problem: if it is the getConnection() call that raises the error, cursor will be undefined, so the reference in the finally block will error.

这篇关于在 try、catch、finally 语句中使用变量而不在外部声明它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆