给出以下Python代码:
# Use impyla package to access Impala
from impala.dbapi import connect
import logging
def process():
conn = connect(host=host, port=port) # Mocking host and port
try:
cursor = conn.cursor()
# Execute query and fetch result
except:
loggin.error("Task failed with some exception")
finally:
cursor.close() # Exception here!
conn.close()
创建了与Impala的连接。但由于Impala超时,cursor.close()
出现了异常。
在给定潜在异常的情况下关闭cursor
和conn
的正确方法是什么?
答案 0 :(得分:2)
你必须嵌套try-blocks:
def process():
conn = connect(host=host, port=port) # Mocking host and port
try:
cursor = conn.cursor()
try:
# Execute query and fetch result
finally:
# here cursor may fail
cursor.close()
except:
loggin.error("Task failed with some exception")
finally:
conn.close()
要避免使用此类try-finally-blocks,您可以使用with
- 语句:
def process():
conn = connect(host=host, port=port) # Mocking host and port
try:
with conn.cursor() as cursor:
# Execute query and fetch result
# cursor is automatically closed
except:
loggin.error("Task failed with some exception")
finally:
conn.close()