[英]NameError: name 'variable' is not defined, how to handle and exception in the finally block of try/except statement
[英]How to handle exception in the “finally” block?
給出以下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
的正確方法是什么?
您必須嵌套try塊:
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,可以將-statement with
語句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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.