In programming, there may be some situation in which the current method ends up while handling some exceptions. But the method may require some additional steps before its termination, like closing a file or a network and so on.
So, in order to handle these situations, Python provides a keyword
finally, which is always executed after
except blocks. The
finally block always executes after normal termination of try block or after try block terminates due to some exception.
try: # Some Code.... except: # optional block # Handling of exception (if required) finally: # Some code .....(always executed)
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.
Can't divide by zero This is always executed
5 This is always executed
This is always executed
Runtime Error –
Unhandled Exception k=5//0 #No exception raised ZeroDivisionError: integer division or modulo by zero
In above code, the exception is generated integer division or modulo by zero, which was not handled. The exception was re-raised after execution of finally block. This shows that finally block is executed regardless of exception is handled or not.
- is keyword in Python
- Python in Keyword
- Python | assert keyword
- Global keyword in Python
- Keyword Module in Python
- Python | yield Keyword
- Use of nonlocal vs use of global keyword in Python
- Python IMDbPY - Searching keyword
- How to check if a string is a valid keyword in Python?
- Python program to check if a given string is Keyword or not
- Python | Passing dictionary as keyword arguments
- Python IMDbPY – Searching movies matching with keyword
- Python - Read blob object in python using wand library
- MySQL-Connector-Python module in Python
- Python | PRAW - Python Reddit API Wrapper
- Reading Python File-Like Objects from C | Python
- twitter-text-python (ttp) module - Python
- Important differences between Python 2.x and Python 3.x with examples
- Python | Index of Non-Zero elements in Python list
- Python | Merge Python key values to list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.