如何处理“finally”块中的异常?

uubf1zoe  于 2021-06-26  发布在  Impala
关注(0)|答案(1)|浏览(306)

给定以下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 超时。
什么是正确的方法来关闭 cursor 以及 conn 考虑到潜在的例外?

ggazkfy8

ggazkfy81#

必须嵌套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块,可以使用 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()

相关问题