The try, except, and finally blocks in Python work together to manage errors and ensure cleanup actions are performed reliably.

try Block: Contains code that might raise an exception. If an exception occurs, execution immediately stops and jumps to the corresponding except block.

except Block: Handles specific exceptions caught from the try block. It allows you to respond gracefully to errors, such as printing a message or using a fallback value.

finally Block: Executes regardless of whether an exception occurred or not. It is ideal for cleanup tasks like closing files, releasing resources, or logging, ensuring these actions always happen, even if an error occurs or a return, break, or continue is used.

For example:

try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found!")
finally:
    file.close()  # Ensures file is closed, even if an error occurred

The finally block runs after the try and except blocks, even if a return statement is encountered in try or except. This makes it a reliable place for critical cleanup.

finally will always run, no matter what the result of try or except is, even if one of them contains break or return def tell_me_about_bad_math(): try: 1/0 except ZeroDivisionError: return 'oops!' finally: print('you did bad math!') print(tell_me_about_bad_math()) Answer from Deleted User on reddit.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › try-except-else-and-finally-in-python
Try, Except, else and Finally in Python - GeeksforGeeks
Example: Let's try to throw the exception in except block and Finally will execute either exception will generate or not ... # Python code to illustrate # working of try() def divide(x, y): try: # Floor Division : Gives only Fractional # Part as Answer result = x // y except ZeroDivisionError: print("Sorry !
Published   July 15, 2025
Discussions

exception - What is the intended use of the optional "else" clause of the "try" statement in Python? - Stack Overflow
It does require at least one preceding except clause (see the grammar). So it really isn't "try-else," it's "try-except-else(-finally)," with the else (and finally) being optional. The Python Tutorial elaborates on the intended usage: More on stackoverflow.com
🌐 stackoverflow.com
python - Order of execution in try except finally - Stack Overflow
I never really use finally, so I wanted to test a few things before using it more regularly. I noticed that when running: def f(): try: 1/0 # 1/1 except: print('exce... More on stackoverflow.com
🌐 stackoverflow.com
For ... except ... finally - Ideas - Discussions on Python.org
While using the instruction for on a generator, I wanted to catch an exception coming from the generator, and I didn’t found a better solution to use a verbose try except around the for, and which becomes complicated when several errors can come from both iteration and content codes. More on discuss.python.org
🌐 discuss.python.org
0
January 22, 2024
Jump statement in try except finally block
Hi all, can someone say why this is stuck in a infinite loop? Code while True: print("why is this happening") try: break finally: continue Output why is this happening why is this happening why is this happening ... More on discuss.python.org
🌐 discuss.python.org
0
2
June 29, 2024
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 documentation
If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.
🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
You can use the else keyword to ... went wrong") Try it Yourself » · The finally block, if specified, will be executed regardless if the try block raises an error or not....
🌐
Plain English
python.plainenglish.io › mastering-pythons-try-except-else-finally-statement-a26a8f123cf7
Mastering Python’s try…except…else…finally Statement | by Allwin Raju | Python in Plain English
November 26, 2024 - Python’s try...except...else...finally block provides a way to manage potential exceptions and handle resources efficiently.
🌐
VR Soft Tech
vrsofttech.com › python › python-exception-handling-try-catch-finally
Exception Handling in Python | vrsofttech
Exception handling is the way to handle the runtime errors.In Python, runtime errors can be handle using try and except block. ... try: #Block of code except: #Handle the error else: #Execute if no exception finally: #Execute always executes
Find elsewhere
Top answer
1 of 16
1149

The statements in the else block are executed if execution falls off the bottom of the try - if there was no exception. Honestly, I've never found a need.

However, Handling Exceptions notes:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.

So, if you have a method that could, for example, throw an IOError, and you want to catch exceptions it raises, but there's something else you want to do if the first operation succeeds, and you don't want to catch an IOError from that operation, you might write something like this:

try:
    operation_that_can_throw_ioerror()
except IOError:
    handle_the_exception_somehow()
else:
    # we don't want to catch the IOError if it's raised
    another_operation_that_can_throw_ioerror()
finally:
    something_we_always_need_to_do()

If you just put another_operation_that_can_throw_ioerror() after operation_that_can_throw_ioerror, the except would catch the second call's errors. And if you put it after the whole try block, it'll always be run, and not until after the finally. The else lets you make sure

  1. the second operation's only run if there's no exception,
  2. it's run before the finally block, and
  3. any IOErrors it raises aren't caught here
2 of 16
172

There is one big reason to use else - style and readability. It's generally a good idea to keep code that can cause exceptions near the code that deals with them. For example, compare these:

try:
    from EasyDialogs import AskPassword
    # 20 other lines
    getpass = AskPassword
except ImportError:
    getpass = default_getpass

and

try:
    from EasyDialogs import AskPassword
except ImportError:
    getpass = default_getpass
else:
    # 20 other lines
    getpass = AskPassword

The second one is good when the except can't return early, or re-throw the exception. If possible, I would have written:

try:
    from EasyDialogs import AskPassword
except ImportError:
    getpass = default_getpass
    return False  # or throw Exception('something more descriptive')

# 20 other lines
getpass = AskPassword

Note: Answer copied from recently-posted duplicate here, hence all this "AskPassword" stuff.

🌐
Medium
codeandcompany.medium.com › exception-handling-in-python-try-except-finally-and-custom-exceptions-590bd4722e4e
Exception Handling in Python: try & except, finally, and custom exceptions | by Code & Company | Medium
August 8, 2023 - Exception Handling in Python: try & except, finally, and custom exceptions Introduction: Exception handling is a fundamental skill for every Python programmer. It allows programmers to handle errors …
🌐
Medium
galea.medium.com › pythons-try-except-else-finally-explained-f04d47d57125
Python’s “try except else finally” explained | by Alex Galea | Medium
October 4, 2020 - Understanding else/finally is simple because there are only two cases. The try statement succeeds -> The except statement is skipped -> The else statement runs -> The finally statement runs
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-keywords
Python Keywords - GeeksforGeeks
December 3, 2025 - They define the rules and structure of Python programs which means you cannot use them as names for your variables, functions, classes or any other identifiers. We can also get all the keyword names using the below code. ... The list of keywords are: ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
🌐
Quora
quora.com › How-does-the-finally-clause-work-in-Pythons-try-except-blocks
How does the finally clause work in Python's try-except blocks? - Quora
Answer: It's a default block of code that executes irrespective of exception. It's generally put after the catch block. It only have some default statements to be executed.
🌐
Python.org
discuss.python.org › ideas
For ... except ... finally - Ideas - Discussions on Python.org
January 22, 2024 - While using the instruction for on a generator, I wanted to catch an exception coming from the generator, and I didn’t found a better solution to use a verbose try except around the for, and which becomes complicated whe…
🌐
Note.nkmk.me
note.nkmk.me › home › python
Try, except, else, finally in Python (Exception handling) | note.nkmk.me
August 15, 2023 - try: for i in [-2, -1, 0, 1, 2]: print(1 / i) except ZeroDivisionError as e: print(e) # -0.5 # -1.0 # division by zero ... You can specify the code to execute after the except clause using the else and finally clauses, which will be described later.
🌐
Tutorialspoint
tutorialspoint.com › home › python › python try except block
Python Try Except Block
February 21, 2009 - The finally clause provides a mechanism to guarantee that specific code will be executed, regardless of whether an exception is raised or not. This is useful for performing cleanup actions such as closing files or network connections, releasing ...
🌐
Server Academy
serveracademy.com › blog › python-try-except
Python Try Except - Server Academy
Python’s except block allows ... provides specific details about the error that occurred. The finally block runs regardless of whether an exception occurs or not....
🌐
Substack
shonistar.substack.com › p › i-coder
I, Coder - by Shoni - Interested in Things
3 weeks ago - Except that when I did that, it tended to break, apparently because of a curly quotes thing that computers automatically do. Like this: “-”, instead of them hanging straight. The fix was for me to copy every piece of code into a .txt document and then copy it into the script. We also had another text file for a thing called content.js. In the beginning, I had to transfer everything from Claude into there too, but then we realised that Claude could access the file directly if I gave it permission, which made things faster and easier.
🌐
Devcuriosity
devcuriosity.com › manual › details › python-try-except-finally-continue-break-loops
Python - Try, Except, Finally, Continue, Break in Loop Control Flow with examples
TypeError · continue - Immediately go to the next loop iteration, skipping any remaining code in the current iteration. (pass is simply doing nothing, they are NOT the same) ... finally - Executes at the end of each try block, whether or not an exception was raised.
🌐
Python.org
discuss.python.org › python help
Jump statement in try except finally block - Python Help - Discussions on Python.org
June 29, 2024 - If the finally clause executes a return, break or continue statement, the saved exception is discarded: ... When a return, break or continue statement is executed in the try suite of a try…finally statement, the finally clause is also executed ‘on the way out.’ The return value of a function is determined by the last return statement executed.
🌐
GUVI
guvi.in › hub › python › try-except-finally-in-python
try…except…finally in Python
This example demonstrates how 'try...except...finally' allows you to handle exceptions and execute critical code in the 'finally' block, ensuring that necessary cleanup or resource management tasks are always performed, even in the presence of exceptions. To conclude, the try...except statement in Python provides a robust and comprehensive approach to exception handling and resource management.