2

Given the following Python code:

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

The connection to Impala was created. But there was an exception in cursor.close() due to Impala timeout.

What is the proper way to close the cursor and conn given the latent exception?

Zelong
  • 2,476
  • 7
  • 31
  • 51
  • move the `conn = connect(host=host, port=port) ` to try block. Exception is getting raised as its out of try block – Tanu May 23 '16 at 05:59
  • 1
    Place the `cursor.close()` in the try block, You must put those things in finally block which are sure not to cause any exception – ZdaR May 23 '16 at 06:00
  • Exception might be generated because, `conn` was never established. Try putting that line again in `try` block. – Jay Patel May 23 '16 at 06:02
  • If you put many things in the try block and one of them generates an exception, you might not know which. Could make life difficult in some circumstances. – user20160 May 23 '16 at 06:04

1 Answers1

5

You have to nest the try-blocks:

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

To avoid such try-finally-blocks, you can use the with-statement:

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()
Daniel
  • 42,087
  • 4
  • 55
  • 81