2016-05-23 9 views
0

den folgenden Python-Code Gegeben:Wie behandelt man die Ausnahme im "finally" -Block?

# 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() 

Die Verbindung zum Impala erstellt wurde. Aber es gab eine Ausnahme in cursor.close() wegen Impala Timeout.

Was ist der richtige Weg, die cursor und conn angesichts der latenten Ausnahme zu schließen?

+0

Bewegung der 'conn = verbinden (Host = Host, Port = Port) 'um Block zu versuchen. Exception wird ausgelöst, da es aus dem try-Block – Tanu

+1

kommt Platziere die 'cursor.close()' im try-Block, Du musst diese Dinge in finally block setzen, die sicher keine Ausnahme verursachen – ZdaR

+0

Exception könnte erzeugt werden, weil 'conn 'wurde nie gegründet. Versuchen Sie, diese Zeile erneut in "try" -Block zu setzen. –

Antwort

2

Sie nisten haben die Try-Blöcke:

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() 

Um dies zu vermeiden versuchen-finally-Blöcke, können Sie die with -Anweisung verwenden:

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() 
Verwandte Themen