How to Handle Exceptions in Python

Learn how to catch and respond to errors in Python so your program does not crash unexpectedly. This page focuses on practical exception handling patterns beginners can use right away.

Quick answer

Use try and except when code might fail because of bad input, missing files, or other runtime problems.

try:
    number = int(input("Enter a number: "))
    print(10 / number)
except ValueError:
    print("Please enter a valid whole number.")
except ZeroDivisionError:
    print("You cannot divide by zero.")

In this example:

  • int(input(...)) can raise a ValueError if the user types text like "abc"
  • 10 / number can raise a ZeroDivisionError if the user enters 0
  • Instead of crashing, the program shows a helpful message

What this page helps you do

This page shows you how to:

  • Catch errors without stopping the whole program
  • Show helpful messages to the user
  • Handle common problems like bad input and missing files
  • Use exception handling in a simple beginner-friendly way

When to use exception handling

Exception handling is useful when your code depends on something that may go wrong at runtime.

Common examples:

  • When user input may be wrong
  • When opening or reading files
  • When converting strings to numbers
  • When code depends on data you do not fully control

For a broader explanation of Python errors, see Python errors and exceptions explained.

Basic try-except structure

The basic pattern looks like this:

try:
    # code that might fail
    pass
except SomeError:
    # what to do if that error happens
    pass

A beginner-friendly example:

text = input("Enter your age: ")

try:
    age = int(text)
    print("Next year you will be", age + 1)
except ValueError:
    print("Please enter a valid number.")

How it works:

  • Put risky code inside try
  • Put the recovery action inside except
  • Keep the code small and focused
  • Catch specific exceptions when possible

In this case, int(text) may fail if the input is not a valid number.

If you want more examples of this pattern, see how to use try-except blocks in Python.

Handle specific exceptions

Catching specific exceptions makes your code easier to understand and debug.

Example: bad number input and division by zero

try:
    number = int(input("Enter a number: "))
    result = 100 / number
    print("Result:", result)
except ValueError:
    print("That was not a valid number.")
except ZeroDivisionError:
    print("You cannot divide by zero.")

This is better than using a broad except because:

  • ValueError handles bad number conversion
  • ZeroDivisionError handles division by zero
  • Each problem gets the right message

If you need help with these specific errors, see:

Example: missing file

try:
    with open("notes.txt", "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("The file was not found.")

This handles a common file problem without crashing.

If you want to learn more about this error, see FileNotFoundError in Python: causes and fixes.

Catch more than one exception

You can use multiple except blocks, or catch several exception types together.

try:
    number = int(input("Enter a number: "))
    print(50 / number)
except (ValueError, ZeroDivisionError):
    print("Please enter a non-zero whole number.")

This is useful when different errors should lead to the same response. For more patterns, see how to catch multiple exceptions in Python.

Use else and finally when needed

You can add else and finally to a try block.

  • Use else for code that should run only if no exception happens
  • Use finally for cleanup code that must always run

Example:

file = None

try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("Could not open the file.")
else:
    print("File contents:")
    print(content)
finally:
    if file is not None:
        file.close()
        print("File closed.")

What happens here:

  • try attempts to open and read the file
  • except handles the missing file case
  • else runs only if the file was opened and read successfully
  • finally runs whether an error happens or not

In many real programs, finally is used for cleanup such as closing files or releasing resources.

For a fuller explanation, see using try, except, else, and finally in Python.

Best practices for beginners

Keep these rules in mind:

  • Do not hide every error with a bare except
  • Print clear messages that explain what went wrong
  • Only wrap the lines that may fail
  • Test both success and failure cases

A good example:

user_input = input("Enter a whole number: ")

try:
    number = int(user_input)
except ValueError:
    print("That input is not a whole number.")
else:
    print("You entered:", number)

Why this is good:

  • The try block is small
  • The exception type is specific
  • The message is clear
  • Normal code stays outside the try when possible

How to debug exception handling

If your exception handling is not working as expected, try these steps:

  • Read the exception name carefully
  • Check the line number in the traceback
  • Print the actual exception object when needed
  • Temporarily remove broad exception blocks if they hide the real problem

Example:

try:
    number = int("hello")
except ValueError as error:
    print("Caught error:", error)

Possible output:

Caught error: invalid literal for int() with base 10: 'hello'

Useful commands and checks:

python your_script.py
python -X dev your_script.py
print(type(value))
print(repr(value))

These can help you inspect what your program is really working with.

Common mistakes

These are common causes of confusing exception handling:

  • Using except without knowing which error the code can raise
  • Catching Exception too early and hiding useful details
  • Putting too much code inside the try block
  • Printing a vague error message that does not help the user
  • Expecting exception handling to fix logic errors automatically

For example, this is too broad:

try:
    number = int(input("Enter a number: "))
    print(100 / number)
except:
    print("Something went wrong.")

Problems with this version:

  • It catches almost everything
  • It hides the real error type
  • The message is too vague to help the user or the programmer

A better version is:

try:
    number = int(input("Enter a number: "))
    print(100 / number)
except ValueError:
    print("Please enter a valid whole number.")
except ZeroDivisionError:
    print("You cannot divide by zero.")

FAQ

What is the difference between try and except?

try contains code that may fail. except contains code that runs if an exception happens.

Should I use a bare except?

Usually no. It catches too many errors and makes debugging harder. Catch specific exceptions instead.

Can I handle more than one exception?

Yes. You can use multiple except blocks or catch a tuple of exception types.

What does finally do?

finally always runs, whether an exception happens or not. It is useful for cleanup.

Is exception handling the same as fixing the problem?

No. It lets your program respond safely, but you still need to understand and fix the cause when necessary.

See also