Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a variable in a try,catch,finally statement without declaring it outside

Tags:

python

scope

I'm pretty new to Python, here is some code I am looking at:

try:     connection = getConnection(database)     cursor = connection.cursor()     cursor.execute("some query") except:     log.error("Problem.")     raise finally:     cursor.close()     connection.close() 

Is that being cleaned up properly? In other languages I have written in, I am used to doing something like this:

connection = None cursor = None  try:     connection = getConnection(database)     cursor = connection.cursor()     cursor.execute("some query") except:     log.error("Problem.")     raise finally:     if cursor is not None:         cursor.close()     if connection is not None:             connection.close() 
like image 913
Cheetah Avatar asked Jun 19 '13 15:06

Cheetah


People also ask

How do you make a variable inside a try except block public?

Solution 1 What you need to do is declare your variable outside of the try scope. Before the try scope so it the variable still exists in your except block. This will raise the exception but x will still have scope (lifetime) and will print out in the 2nd exception case.

Why variables defined in try Cannot be used in catch or finally in Java?

Variables in try block So, if you declare a variable in try block, (for that matter in any block) it will be local to that particular block, the life time of the variable expires after the execution of the block. Therefore, you cannot access any variable declared in a block, outside it.

Can we declare variable in catch block?

Variables declared within the try/catch block are not in scope in the containing block, for the same reason that all other variable declarations are local to the scope in which they occur: That's how the specification defines it. :-) (More below, including a reply to your comment.)


1 Answers

Python does not have block scope. Anything defined inside the try block will be available outside.

That said, you would still have a problem: if it is the getConnection() call that raises the error, cursor will be undefined, so the reference in the finally block will error.

like image 80
Daniel Roseman Avatar answered Sep 21 '22 10:09

Daniel Roseman