i

Python Programming

The try-finally Clause

Finally block along with a try block. The finally block is place to put any code that execute, whether try-block raised exception or not. The syntax of the try/finally statement is :

try:

   You do operations here

   Due to exception, this may skipped.

finally:

   This would always execute

You can’t use else clause as well along with finally clause.

Example

Live Demo

You do not have permission to open file in writing mode, then this will produce following

Output:

Error: can't find file or read data

The same example can be written more cleanly:

Live Demo

When an exception is thrown in try/block, the execution immediately passes to final block. After all statements in the finally, block executed, the exception is raised again and handled in the except statements if present in next higher layer of try/except statement.