Python try-finally block

Python try-finally block

You can use a finally block after a try block. In the finally block, you can place any code that must execute regardless of whether the try block raises an exception.

The syntax of the try-finally statement is as follows:

try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................

Note − You can provide either an except clause or a finally clause, but not both. You cannot use an else clause with a finally clause.

Example

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print("Error: can't find file or read data")
fh.close()

If you do not have permission to open the file in write mode, the following output will be produced.

Error: can't find file or read data

The same example can be written more clearly as follows –

try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print("Going to close the file")
fh.close()
except IOError:
print("Error: can't find file or read data")

When an exception is thrown in a try block, execution immediately transfers to the finally block. After all statements in the finally block are executed, the exception is re-raised and handled in the next higher-level except statement in the try-except statement (if any).

Exceptions with Arguments

Exceptions can have an argument, a value that provides additional information about the problem. The contents of the argument vary depending on the exception. You can capture the exception’s argument by providing a variable in the except clause, as shown below −

try:
You do your operations here
......................
except ExceptionType as Argument:
You can print the value of Argument here...

If you are writing code to handle a single exception, you can include a variable following the exception name in the except clause. If you are catching multiple exceptions, you can include a variable following a tuple of exceptions.

This variable receives the value of the exception, which typically contains the cause of the exception. This variable can receive a single value or a tuple of values. This tuple typically contains the error string, error number, and error location.

Example

The following is an example of handling a single exception –

# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError as Argument:
print("The argument does not contain numbers",Argument)
# Call the above function here.
temp_convert("xyz")

It will produce the following output −

The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'

Leave a Reply

Your email address will not be published. Required fields are marked *