簡體   English   中英

如何在“ finally”塊中處理異常?

[英]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()有一個異常。

給定潛在異常,關閉cursorconn的正確方法是什么?

您必須嵌套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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM