473,387 Members | 1,724 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

What is "finally:" for?

Hi all!
When and where I should use try-except-finally statement? What is the
difference between:
--------
try:
A...
except:
B....
finally:
C...
--------

and
-------
try:
A...
except:
B....
C...
Sep 16 '08 #1
5 1715
On 16 Sep., 13:25, "Max Ivanov" <ivanov.ma...@gmail.comwrote:
Hi all!
When and where I should use try-except-finally statement? What is the
difference between:
--------
try:
* A...
except:
* B....
finally:
* C...
--------
It does A if no exception or B if an exception occurs. THEN it does
always C.
>
and
-------
try:
* A...
except:
* B....
C...
If an exception occurs, C is never reaching.

Andreas
Sep 16 '08 #2
On 16 Sep., 13:25, "Max Ivanov" <ivanov.ma...@gmail.comwrote:
Hi all!
When and where I should use try-except-finally statement? What is the
difference between:
--------
try:
* A...
except:
* B....
finally:
* C...
--------

and
-------
try:
* A...
except:
* B....
C...
Look at: http://docs.python.org/ref/try.html and http://bytes.com/forum/thread24648.html

The python doc says:
"Changed in version 2.5: In previous versions of Python,
try...except...finally did not work. try...except had to be nested in
try...finally."

Andreas
Sep 16 '08 #3
On Sep 16, 6:25*am, "Max Ivanov" <ivanov.ma...@gmail.comwrote:
Hi all!
When and where I should use try-except-finally statement? What is the
difference between:
--------
try:
* A...
except:
* B....
finally:
* C...
--------

and
-------
try:
* A...
except:
* B....
C...
If B raises or rethrows another exception, finally: ensures that C
still gets called. In the second form that you give, C would not get
called. Here is one way to use try-except-finally:

try:
open database
do database stuff
except DatabaseException, de:
log exception
throw
finally:
close database

Or

try:
transaction = new database transaction
do database stuff
do more database stuff
commit transaction
transaction = None
except DatabaseException, de:
log exception
throw
finally:
if transaction:
rollback transaction
If you are allocating a resource, lock, file, database, etc., then
exception-safe coding style is to get the resource in a try: and
release the resource in finally:

-- Paul
Sep 16 '08 #4
Ant
On Sep 16, 12:30*pm, Andreas Kaiser <kaiser.voc...@gmail.comwrote:
On 16 Sep., 13:25, "Max Ivanov" <ivanov.ma...@gmail.comwrote:Hi all!
When and where I should use try-except-finally statement? What is the
difference between:
--------
try:
* A...
except:
* B....
finally:
* C...
--------

It does A if no exception or B if an exception occurs. THEN it does
always C.
Rather it runs the code in A. If an exception is thrown in A, B is
then run. C is run regardless.
-------
try:
* A...
except:
* B....
C...

If an exception occurs, C is never reaching.
Whether or not C runs will depend on what code is present in B (e.g.
it could return, or throw a different exception).

Typically you will use a finally clause if there is some cleanup that
should occur regardless of whether an exception is thrown. For
example:

def getNumbers(filename):
numbers = []

fh = open("test.txt") # Should contain lines of numbers
try:
for line in fh:
if line.strip():
numbers.append(int(line.strip()))
except ValueError, e:
return None
finally:
fh.close()

return numbers
This ensures that open files are closed for example.

--
Ant.
Sep 16 '08 #5
Paul McGuire wrote:
....
try:
open database
do database stuff
except DatabaseException, de:
log exception
throw
finally:
close database

Or

try:
transaction = new database transaction
do database stuff
do more database stuff
commit transaction
transaction = None
except DatabaseException, de:
log exception
throw
finally:
if transaction:
rollback transaction
Generally it is a good idea to try the advice you are about to offer.

"raise" is the Python way to do the Lisp/Scheme "throw" which will
likely produce another error, but not the one you want.

--Scott David Daniels
Sc***********@Acm.Org
Sep 17 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

77
by: Jon Skeet [C# MVP] | last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the article on all the groups this is posted to. I've finally managed to finish my article on multi-threading - at least for...
10
by: Joe Thompson | last post by:
Hi, This is probably a simple question but I'm curious. What is the purpose of the "finally" statement? There must be a good reason to use it that I'm just not getting... How is this: ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.