Python for AIPython for AI
Python Basics

Try and except

Catch errors before they crash

When your Python program runs into an unexpected problem, it "raises an exception." This stops your code right in its tracks! But you can catch these exceptions and handle them gracefully.

Basic try-except structure

The simplest way to catch a problem is with a try and except block. You put the code that might cause trouble inside the try block. If an error happens, the code in the except block runs instead of crashing your program.

python
try:
    result = 10 / 0  # This will cause an error!
    print(result)
except:
    print("Oops! Something went wrong.")

print("Program continues here.")

In the example, dividing by zero (10 / 0) is an error. Without try-except, your program would stop. With it, you see the friendly message and the program keeps going.

Catching specific errors

It's a good practice to catch specific types of errors. This helps you respond more accurately to problems and avoids hiding unexpected bugs. You can specify the error type after except.

python
try:
    number = int("hello") # This will cause a ValueError
    print(number)
except ValueError:
    print("That wasn't a valid number!")
except ZeroDivisionError:
    print("Can't divide by zero!")

Here, if int("hello") fails, it raises a ValueError. Our except ValueError block catches it. If we had tried to divide by zero, the ZeroDivisionError block would respond instead.

Multiple error types

You can catch multiple specific error types. You can list them in different except blocks, or combine them into one.

python
try:
    # code that might raise ValueError or TypeError
    my_list = [1, 2, 3]
    print(my_list["a"]) # TypeError for invalid index
except (ValueError, TypeError):
    print("Caught either a Value or Type error!")

Enclosing the error types in parentheses makes it a tuple, allowing a single except block to handle any of them.

The else clause

What if no error happens? You might want to run some code only when the try block completes successfully. That's what the else clause is for.

python
try:
    numerator = 10
    denominator = 2
    result = numerator / denominator
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print(f"The division result is: {result}")
    print("No errors occurred!")

The code in the else block will only run if the try block finishes without any exceptions.

The finally clause

Sometimes you have cleanup tasks, like closing a file, that *must* happen whether an error occurred or not. The finally block is perfect for this.

python
file = None
try:
    file = open("my_data.txt", "r") # This file might not exist
    content = file.read()
    print(content)
except FileNotFoundError:
    print("File not found! Creating it...")
    file = open("my_data.txt", "w")
    file.write("Hello, world!")
finally:
    if file:
        file.close()
    print("File operation attempt complete.")

The finally block always executes, even if an exception was caught or if no exception happened at all. It's great for ensuring resources are properly released.

Common mistakes

  • Catching too broadly: Using a bare except: without specifying an error type can hide real problems in your code.
  • Putting too much in try: Only put the code that might specifically raise an error inside try to keep your error handling focused.
  • Ignoring exceptions: Just catching an error and doing nothing (except: pass) can make debugging very difficult later on.

Practice

Try these exercises to lock in what you just learned.

Quiz
Not started
Which block catches an exception?
Code challenge
Not started
Catch ZeroDivisionError when dividing 1/0 and print: caught

What's next?

You've learned how to make your Python programs more robust by catching errors. This is a fundamental skill for writing reliable software. Keep practicing with different types of errors to get comfortable with try-except blocks.