For more information on topics covered in this lesson, check out these resources:
Using return With try and finally Blocks
In Python, when you write code that you know may cause an exception, you typically use it with a
try statement. One of the features of a
try statement is an optional
finally clause, which is executed whether or not there was actually an exception.
Real Python has an introduction to exceptions tutorial, where you can read more information about the
try statement. In this lesson, we’ll be looking specifically at using the
return statement and
try statements that have a
Simply put, when you use a
return statement inside a
try statement that has a
finally clause, that
finally clause is always executed before the
return statement. Specifically, this means that the
finally clause will always be executed when the
try statement is encountered.
If the statement is successful, then the floating-point value it represents will be returned. If it is unsuccessful, then a
ValueError will occur, and the
return statement in the
except clause will be executed, which returns the argument in
values as a string.
In either case, since this
try statement has a
finally clause, it will be executed before the function returns. So for any argument in
value, we will see the phrase
Run this before returning printed before the function ends. And in an interactive session, we’ll see the return value after that print statement.
So remember that any code that is in a
finally clause will always be executed before any
return statements in either the
except clauses. In your last lesson, we will look at using the
return statement in generator functions.
Become a Member to join the conversation.