Finally keyword in Python
Last Updated : 26 Feb, 2025
In Python, the finally keyword is used in a try-except-finally block to define a section of code that will always execute, regardless of whether an exception occurs or not. It guarantees predictable code behavior, maintaining program stability even when errors arise. By using finally
, developers ensure that cleanup operations and essential tasks are consistently performed, promoting code reliability and readability.
Example:
Python try: result = 10 / 0 except ZeroDivisionError: print("Caught division by zero error.") finally: print("This block always executes.")
OutputCaught division by zero error. This block always executes.
Important Points -
- finally block is always executed after leaving the try statement. In case if some exception was not handled by except block, it is re-raised after execution of finally block.
- finally block is used to deallocate the system resources.
- One can use finally just after try without using except block, but no exception is handled in that case.
Syntax
try:
# Code that may raise an exception
except ExceptionType:
# Code that handles the exception
finally:
# Code that always executes
- Parameters: finally block does not accept any parameters.
- Return type: finally block does not return any value; it is used solely for executing cleanup code.
Examples
This example demonstrates the finally block executing after an exception is raised and handled.
Python try: k = 5 // 0 except ZeroDivisionError: print("Can't divide by zero") finally: print('This is always executed')
OutputCan't divide by zero This is always executed
Explanation: The ZeroDivisionError is caught in the except block, printing a message. Regardless of the exception, the finally block executes, ensuring that the cleanup or final statement runs.
Example 2: No Exception Occurs
This example shows that the finally
block executes even when no exception occurs.
Python try: k = 5 // 1 print(k) finally: print('This is always executed')
Output5 This is always executed
Explanation: The try
block executes without any errors, so the except
block is skipped. However, the finally
block still runs, demonstrating its unconditional execution.
Example 3: Unhandled Exception
In this example, the exception is not caught, but the finally
block still executes.
Python try: k = 5 // 0 finally: print('This is always executed')
Unhandled ExceptionExplanation: The division by zero causes a ZeroDivisionError
, which is not handled. Despite this, the finally
block executes before the program terminates with an error.
This example shows that the finally
block executes before the return statement.
Python def learnfinally(): try: print("Inside try Block") return 1 finally: print("Inside Finally") print(learnfinally())
OutputInside try Block Inside Finally 1
Explanation: Although the try
block has a return
statement, the finally
block executes before the function returns the value. This demonstrates that finally
has priority over control flow statements like return
.
Similar Reads
is keyword in Python In programming, a keyword is a âreserved wordâ by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. Python language also reserves some of the keywords that convey special meaning. In Py
2 min read
Python in Keyword The in keyword in Python is a powerful operator used for membership testing and iteration. It helps determine whether an element exists within a given sequence, such as a list, tuple, string, set or dictionary.Example:Pythons = "Geeks for geeks" if "for" in s: print("found") else: print("not found")
3 min read
Keywords in Python | Set 2 Python Keywords - Introduction Keywords in Python | Set 1 More keywords:16. try : This keyword is used for exception handling, used to catch the errors in the code using the keyword except. Code in "try" block is checked, if there is any type of error, except block is executed. 17. except : As expl
4 min read
re.findall() in Python re.findall() method in Python helps us find all pattern occurrences in a string. It's like searching through a sentence to find every word that matches a specific rule. We can do this using regular expressions (regex) to create the pattern and then use re.findall() to get a list of matches.Let's say
2 min read
Python Keywords Keywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. Python keywords cannot be used as the names of variables, functions, and classes or any other identifier. Getting List of all Python keywordsWe can also get all the keyword names usin
2 min read