2016-05-23 38 views
0

鑑於以下Python代碼:如何處理「finally」塊中的異常?

# 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()出現異常。

鑑於潛在的例外情況,關閉cursorconn的正確方法是什麼?

+0

招'參數conn =連接( host = host,port = port)'嘗試阻止。異常越來越大,因爲它的try塊出來 – Tanu

+1

將'cursor.close()'放在try塊中,你必須把這些東西放在finally塊中,肯定不會引起任何異常 – ZdaR

+0

可能會產生異常,因爲''conn '從未成立。嘗試再次將該行放在'try'塊中。 –

回答

2

你必須嵌套在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() 

爲了避免這樣的嘗試,終於塊,你可以使用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()