Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Keywords in Python | Set 2
Next article icon

Finally keyword in Python

Last Updated : 26 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.") 

Output
Caught 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

Example 1: Handling ZeroDivisionError

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') 

Output
Can'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') 

Output
5 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') 
Screenshot-2025-02-22-153635

Unhandled Exception

Explanation: The division by zero causes a ZeroDivisionError, which is not handled. Despite this, the finally block executes before the program terminates with an error.

Example 4: Interaction with Return Statement

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()) 

Output
Inside 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.



Next Article
Keywords in Python | Set 2
author
deepak_jain
Improve
Article Tags :
  • Python
  • Python-exceptions
Practice Tags :
  • python

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: [GFGTABS] Python s = "Geeks for geeks" if "for" in s: print(
    3 min read
  • as Keyword - Python
    as keyword in Python plays a important role in simplifying code, making it more readable and avoiding potential naming conflicts. It is mainly used to create aliases for modules, exceptions and file operations. This powerful feature reduces verbosity, helps in naming clarity and can be essential whe
    3 min read
  • Python def Keyword
    Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In Python, a function is a logical unit of code containing a sequence of statements indented under a name given using the “def” keyword. In Python def
    6 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 sa
    2 min read
  • python class keyword
    In python class keyword is used to create a class, which acts as a blueprint for creating objects. A class contains attributes and methods that define the characteristics of the objects created from it. This allows us to model real-world entities as objects with their own properties and behaviors. S
    1 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. List of Keywords in PythonTrueFalseNoneandornotisifelseelifforwhilebreakconti
    12 min read
  • Keyword Module in Python
    Python provides an in-built module keyword that allows you to know about the reserved keywords of python. The keyword module allows you the functionality to know about the reserved words or keywords of Python and to check whether the value of a variable is a reserved word or not. In case you are una
    2 min read
  • Python Keywords and Identifiers
    Every language contains words and a set of rules that would make a sentence meaningful. Similarly, in Python programming language, there are a set of predefined words, called Keywords which along with Identifiers will form meaningful sentences when used together. Python keywords cannot be used as th
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences