Skip to content

Python try-finally

  • by

You can use Python try-finally block without expect block for exception handling. The Finally block code must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this:-

try:
   # this can be skipped.
finally:
   # This code executed.

Python try-finally

Simple example code.

try:
    fh = open("hello", "w")
    fh.write("Hello file")
finally:
    print("Error: can\'t find file or read data")
    print("I am finally block")

Output:

Python try-finally

Detailed code

try:
   fh = open("testfile", "w")
   try:
      fh.write("Hello!!")
   finally:
      print "Closing the file"
      fh.close()
except IOError:
   print "Error: can\'t find file or read data"

Why do we need the “finally” clause in Python?

Answer: It makes a difference if you return early:

try:
    run_code1()
except TypeError:
    run_code2()
    return None   # The finally block is run before the method returns
finally:
    other_code()

Compare to this:

try:
    run_code1()
except TypeError:
    run_code2()
    return None   

other_code()  # This doesn't get run if there's an exception.

Other situations that can cause differences:

  • If an exception is thrown inside the except block.
  • If an exception is thrown in run_code1() but it’s not a TypeError.
  • Other controls flow statements such as continue and break statements.

Source: https://stackoverflow.com/questions/11551996/

Do comment if you have any doubts or suggestions on this Python exception-handling topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading