Python try, except, else, and finally: How Exception Handling Works

try, except, else, and finally are Python’s main tools for handling errors without crashing your program. Use them when code might fail and you want to recover, report a clear message, or clean up resources no matter what happens. This article shows the exact control flow, the differences between the clauses, and the mistakes beginners make most often.

Difficulty: Beginner

Helpful to know first: basic Python syntax, how functions work, and what exceptions are.

How try, except, else, and finally Work Together

Python uses exception handling to separate normal code from error handling code. Put the code that might fail inside try, handle specific failures in except, run success-only code in else, and put cleanup code in finally.

The simplest pattern looks like this:

Python
try:
    number = int("42")
except ValueError:
    print("That was not a valid integer.")
else:
    print("Converted successfully:", number)
finally:
    print("Done.")

If the conversion succeeds, the else block runs and then finally runs. If the conversion fails with ValueError, the except block runs and then finally still runs.

When Each Clause Runs

The four clauses are not interchangeable. Each one has a specific job, and Python follows a strict order.

  • try: run code that might raise an exception.
  • except: run only if an exception from the try block matches.
  • else: run only if the try block finished without an exception.
  • finally: run whether an exception happened or not, even if you return from the function.

A single try statement can have multiple except clauses, one else clause, and one finally clause.

Real Examples of try, except, else, and finally

Handling bad user input safely

When a user types text into a program, conversion can fail. This example converts a string to an integer and handles invalid input without stopping the program.

Python
text = "abc"

try:
    age = int(text)
except ValueError:
    print("Please enter a whole number.")
else:
    print("Age:", age)
finally:
    print("Finished checking input.")

# Output:
# Please enter a whole number.
# Finished checking input.

Here, int(text) fails because "abc" is not a valid integer. The except block handles that problem, and finally still runs.

Using else for code that should run only on success

Put follow-up work in else when it should happen only if no exception was raised. This keeps the success path separate from the error path.

Python
try:
    value = int("7")
except ValueError:
    print("Invalid number.")
else:
    print("Squared value:", value * value)

# Output:
# Squared value: 49

This version is easier to read than putting the square calculation inside the try block, because only the conversion can fail. The else block makes that boundary clear.

Cleaning up resources with finally

Use finally for cleanup that must happen even when an error occurs. A common example is closing a file or releasing a lock.

Python
file = None

try:
    file = open("example.txt", "w", encoding="utf-8")
    print("Hello, file!", file)
finally:
    if file is not None:
        file.close()

# Output:
# Hello, file! <_io.TextIOWrapper name='example.txt' mode='w' encoding='utf-8'>

The file is closed even if something inside try raises an exception. For files, the with statement is usually better, but finally shows the underlying idea clearly.

Handling multiple possible errors

You can catch more than one exception type. This is useful when different failures need different messages or recovery steps.

Python
try:
    items = ["red", "green"]
    print(items[5])
except IndexError:
    print("That position does not exist.")
except TypeError:
    print("The index must be an integer.")

# Output:
# That position does not exist.

Each except matches one exception type. Python stops at the first matching handler.

How the Control Flow Actually Works

Python checks the try block from top to bottom. If nothing goes wrong, it skips all except blocks, runs else if present, and then runs finally if present. If an exception occurs, Python looks for the first matching except. If a handler is found, that handler runs and then finally runs. If no handler matches, the exception keeps going after finally finishes.

Two details matter a lot:

  • else never runs after an exception.
  • finally runs even if the function uses return inside try or except.

That is why else is a good place for code that should only run after a successful try. It keeps the success path separate from the error path and avoids catching exceptions from code that should not be treated as part of the risky operation.

Predict the Output

These short snippets test two misunderstandings: whether else runs after an exception is handled, and whether finally can override a return.

Predict the output: handled exception and else

What does this print?

Python
try:
    print(10 / 0)
except ZeroDivisionError:
    print("division failed")
else:
    print("division worked")
finally:
    print("cleanup")
Show answer

It prints:

Python
division failed
cleanup

The division by zero raises ZeroDivisionError, so the except block runs. Because the try block did not finish successfully, else is skipped. finally always runs, so it prints last.

Predict the output: return inside try and finally

What happens when the function returns from try?

Python
def demo() -> int:
    try:
        return 1
    finally:
        print("always runs")

print(demo())
Show answer

It prints:

Python
always runs
1

The return value is prepared first, but Python still executes finally before the function actually finishes. After the cleanup print, the function returns 1.

Common Mistakes With try, except, else, and finally

Catching every exception when you only expect one

Beginners often write a broad except Exception: or even a bare except: because it seems easier. That can hide bugs that should stop the program.

Problem: This handler catches more than the conversion error you expected, so unrelated bugs can disappear and become hard to debug.

Python
try:
    number = int("12")
    print(10 / 0)
except:
    print("Something went wrong.")

Fix: Catch the specific exception you know how to handle.

Python
try:
    number = int("12")
    print(10 / 0)
except ZeroDivisionError:
    print("Cannot divide by zero.")

The corrected version only handles the error it understands, so other problems still show up normally.

Putting success code in except instead of else

If you place normal follow-up work inside except, it only runs when there is an error. That is the opposite of what many beginners intend.

Problem: This code prints the success message only when the conversion fails, because it is inside the error handler.

Python
try:
    temperature = int("21")
except ValueError:
    print("Temperature accepted.")

Fix: Put success-only code in else.

Python
try:
    temperature = int("21")
except ValueError:
    print("Please enter a valid number.")
else:
    print("Temperature accepted.")

The fixed version matches the intent: the message appears only after a successful conversion.

Forgetting that finally still runs after return

Some code assumes finally only matters when an error happens. In reality, it runs after normal completion too.

Problem: A return does not skip finally, so this cleanup still happens before the function ends.

Python
def status() -> str:
    try:
        return "ready"
    finally:
        print("cleaning up")

print(status())

Fix: Use finally only for cleanup, not for logic that should be skipped on return.

Python
def status() -> str:
    try:
        return "ready"
    finally:
        print("cleaning up")

print("done")
print(status())

The corrected version keeps cleanup separate from the returned result, which is what finally is for.

Using a variable set only inside try after a failure

If assignment happens only inside try and that assignment fails, the variable may never be created. Reading it later can raise a new error.

Problem: If int() fails, value is never assigned, so the later print can raise UnboundLocalError or NameError depending on scope.

Python
def parse_number() -> None:
    try:
        value = int("not a number")
    except ValueError:
        print("Could not parse.")
    print(value)

parse_number()

Fix: Initialize the variable before the try block or return early in the exception handler.

Python
def parse_number() -> None:
    value = None
    try:
        value = int("not a number")
    except ValueError:
        print("Could not parse.")
        return
    print(value)

parse_number()

The fixed version avoids reading a variable that was never assigned.

How to Choose Between try/except and Other Patterns

Exception handling is the right tool when a failure is possible, normal, and best handled near the point where it happens. It is not the right tool for every branch.

SituationPreferred approachWhy
Input may not be a valid numbertry/except around int()The failure depends on the actual input.
You want to check before doing somethingif statementUse a normal branch when you can test the condition directly.
You need cleanup for files, locks, or connectionsfinally or withCleanup should happen even if something fails.
You want to continue after a specific errorSpecific except handlerCatch only the error you can handle.

For files, prefer with most of the time because it is simpler and less error-prone than manually opening a file in try and closing it in finally. Use finally when you are teaching the mechanism or when you need more than one cleanup action around a block of code.

Interview Questions About Python Exception Handling

Why use else instead of putting code after the try/except block?

else clearly separates success-only code from error-handling code. It also avoids catching exceptions from later lines that are not part of the risky operation.

Can finally suppress an exception?

Normally, no. finally runs after the exception is handled or propagated. If finally itself raises a new exception or returns a value from a function, that can change the outcome, so it should be used carefully.

Should I catch Exception or a specific error?

Catch specific exceptions whenever possible. Catching Exception is sometimes acceptable at a top-level boundary, such as a command-line entry point, but it is too broad for ordinary program logic.

Try It Yourself

Write a small program that reads three text values, converts them to integers, and prints their sum.

  • If a value cannot be converted, print Invalid number and stop.
  • If all three conversions succeed, print Sum: X, where X is the total.
  • Always print Done at the end.

Expected output:

Python
Sum: 60
Done

Hint: Put the three conversions inside try, the sum print in else, and the final message in finally.

Show solution
Python
values = ["10", "20", "30"]

try:
    a = int(values[0])
    b = int(values[1])
    c = int(values[2])
except ValueError:
    print("Invalid number")
else:
    print("Sum:", a + b + c)
finally:
    print("Done")

Summary

  • try holds code that might fail.
  • except runs only when a matching exception happens.
  • else runs only when the try block succeeds.
  • finally runs whether an exception happens or not.
  • Catch specific exceptions when possible; avoid hiding real bugs with a broad handler.
  • Use finally for cleanup, and use with for resources like files when it fits better.

Next, learn Python’s raise statement so you can create your own exceptions when a function needs to report a failure.