2016-05-23 35 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()