How to Use try-except Blocks in Python

Learn how to catch errors in Python with try-except blocks so your program does not stop unexpectedly. This page focuses on the basic pattern, when to use it, and beginner-friendly examples.

Quick example

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

Use try for code that may fail, and except for the specific errors you want to handle.

What this page helps you do

  • Use a try-except block to handle errors safely
  • Catch common beginner errors without crashing the program
  • Understand the difference between try and except
  • See when to catch one error or multiple errors

Basic try-except structure

A try-except block lets you run code that might fail.

  • Put risky code inside the try block
  • Put error-handling code inside the except block
  • If no error happens, the except block is skipped
  • If an error happens, Python jumps to the matching except block

Here is the basic pattern:

try:
    # code that may raise an error
    pass
except SomeError:
    # code that runs if that error happens
    pass

Example

try:
    result = 10 / 0
    print(result)
except ZeroDivisionError:
    print("You cannot divide by zero.")

What happens here

  • Python tries to run 10 / 0
  • That raises a ZeroDivisionError
  • Python skips the rest of the try block
  • Python runs the matching except block instead

Output:

You cannot divide by zero.

If you are new to exceptions, see Python errors and exceptions explained.

Simple example with user input

A common beginner problem is converting input to a number.

The input() function always returns text. If the text is not a valid integer, int() raises a ValueError.

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

Why this works

  • input("Enter your age: ") gets text from the user
  • int(...) tries to turn that text into an integer
  • If the user enters something like abc, Python raises ValueError
  • The except ValueError block shows a helpful message

Example runs

If the user enters 25:

Enter your age: 25
Next year you will be 26

If the user enters abc:

Enter your age: abc
Please enter a valid whole number.

If you want to learn more about converting input, see how to convert user input to numbers in Python and the Python int() function explained.

Catching more than one error

Sometimes more than one kind of error can happen.

For example:

  • int(input(...)) can raise ValueError
  • dividing by that number can raise ZeroDivisionError

Use separate except blocks when you want different messages or actions.

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

Why separate blocks are useful

  • ValueError means the input could not be converted
  • ZeroDivisionError means the number was 0
  • Each error gets a clear message

This is better than using a broad except because you know exactly what went wrong.

If you want more examples, see how to catch multiple exceptions in Python and how to fix ZeroDivisionError: division by zero.

When to use try-except

Use try-except when you expect a known operation might fail.

Good examples:

  • Reading user input
  • Opening files
  • Converting text to numbers
  • Doing calculations that may divide by zero

Use it around code you expect might raise a known exception.

Avoid wrapping large parts of your program without a clear reason. If too much code is inside one try block, it becomes harder to tell which line failed.

A good rule:

  • Catch only errors you can respond to usefully
  • Keep the try block as small as possible
  • Prefer specific exceptions over a plain except

Common beginner mistakes

Here are some common causes of problems with try-except:

  • Trying to convert invalid text with int()
  • Dividing by zero inside the try block
  • Catching Exception too broadly and hiding the real bug
  • Placing unrelated code inside one large try block
  • Using the wrong exception type in except

Mistake: using a plain except block

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

This works, but it is usually not a good idea for beginners.

Why?

  • It hides the real error type
  • It makes debugging harder
  • It may catch unexpected bugs you did not mean to handle

Prefer this:

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

Mistake: putting too much code inside try

Less helpful:

try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print("Result:", result)
    print("The length is", len(result))
except ValueError:
    print("Invalid number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")

The problem is that len(result) is also inside the try block. If that line fails, your error handling may not match the real problem clearly.

Keep the risky part focused.

How to debug a try-except block

If your try-except block is not behaving as expected, use these steps:

  • Read the exception name carefully
  • Temporarily remove the except block to see the full traceback
  • Print values before the line that fails
  • Check that you are catching the correct exception type

Useful commands and checks:

python script.py
print(type(value))
print(value)
help(ValueError)
help(ZeroDivisionError)

Example debugging idea

If this code does not work:

value = input("Enter a number: ")

try:
    number = int(value)
    print(10 / number)
except ValueError:
    print("Invalid input.")

You should ask:

  • Could the value be 0?
  • If so, should you also catch ZeroDivisionError?

A corrected version:

value = input("Enter a number: ")

try:
    number = int(value)
    print(10 / number)
except ValueError:
    print("Invalid input.")
except ZeroDivisionError:
    print("You cannot divide by zero.")

If you are seeing a specific conversion error, see how to fix ValueError: invalid literal for int() with base 10.

FAQ

What does try-except do in Python?

It lets your program catch an error and handle it with a message or another action instead of stopping immediately.

Should I use a plain except block?

Usually no. It is better to catch specific exceptions like ValueError or ZeroDivisionError.

Can I catch multiple exceptions?

Yes. You can use multiple except blocks or catch more than one exception type when the handling is the same.

Does try-except prevent all crashes?

No. It only handles the exceptions you catch, and it does not fix logic mistakes automatically.

See also

Practice idea: wrap one small input example or file example in a try-except block first. Then move on to else and finally when you want more control over what happens after success or failure.