2

给定以下 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 的连接已创建。cursor.close()但是由于 Impala 超时而出现异常。

鉴于潜在异常,关闭cursorand的正确方法是什么?conn

4

1 回答 1

3

您必须嵌套 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-statement:

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()
于 2016-05-23T06:06:10.197 回答