Finally Keywords In Python. Topic-27

Finally keyword in python

In Python, the finally  keyword is usually used in the context of exception handling. It is utilized alongside try and except blocks to make sure a given set of codes is executed whether an exception happens or not. The finally block is widely used for tasks such as clean-up operations or finalization steps.

Let’s see the syntax:

Syntax
try:
    # Statements that might raise an exception
except ExceptionType:
    # Handling the exception
else:
    # Executed if no exception occurs
finally:
    # Code that always executes, whether an exception occurs or not
Python

  • If an exception of a specific type occurs in the try block, it will be caught and handled in the except block.
  • An else block is executed if an exception does not occur within the function body.
  • The finally block will always run regardless of whether or not an exception was raised. This is common for clean-up tasks or finalization obligations.

For example:

try:
    num = int(input("Enter an integer: "))
except ValueError:
    print("Number entered is not an integer.")
else:
    print("Integer Accepted.")
finally:
    print("This block is always executed.")
Python

The Output Of This Code Will Be:

Output
Enter an integer: 2.5
Number entered is not an integer.
This block is always executed.
Python

In this example, if the user enters a non-integer value, the except block is executed and then executes the finally block. If the user enters an integer, else block gets executed first before executing finally block.

This feature ensures that whatever code is inside the finally block always runs which makes it very important for jobs that must be done regardless of whether exceptions arise or not.

If you don’t know the For Loop With Else In Python” just click on Read More.

I hope you understand “Finally Keywords In Python” Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

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

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog