finally block in python

Previous
Next

Finally block:

  • “finally” is a keyword.
  • “finally” block is used to provide “Resource releasing logic”.
  • All resources (connected to program) must be closed from finally block.

Note: Finally block executes whether or not an exception has raised in the try block.

class Finally:
    def main():
        try:
            x = 10/5
            print("Try block")

        except Exception:
            print("Except block")

        finally:
            print("Finally block")

        return

Finally.main()

If exception has raised in the try block, the control moves to except block and then to finally block:

class Finally:
    def main():
        try:
            x = 10/0
            print("Try block")

        except Exception:
            print("Except block")

        finally:
            print("Finally block")

        return

Finally.main()
Previous
Next

Add Comment

Courses Enquiry Form