0Pricing
Learn AI with Python · Lesson

Using try, except, and finally

Master error-handling blocks to catch and respond to exceptions.

Using try, except, and finally is a free Learn AI with Python lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn AI with Python learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

1

Introduction to try, except, and finally

Error handling in Python is done using try, except, and finally blocks. These blocks allow you to handle exceptions and ensure resources are properly cleaned up.

In this lesson, you’ll learn how to use these blocks effectively.

Using try, except, and finally — illustration 1

2

The try Block

The try block contains code that might raise an exception. If an exception occurs, Python stops executing the try block and moves to the except block.

# Example of a try block
try:
    x = 10 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError:
    print("You cannot divide by zero.")

3

The except Block

The except block is used to catch and handle exceptions raised in the try block:

# Handling a specific exception
try:
    value = int("abc")  # This will raise a ValueError
except ValueError:
    print("Invalid input. Please enter a number.")

4

Handling Multiple Exceptions

You can handle multiple exceptions by specifying multiple except blocks:

# Handling multiple exceptions
try:
    file = open("nonexistent.txt", "r")
except FileNotFoundError:
    print("The file does not exist.")
except PermissionError:
    print("You don’t have permission to open this file.")

5

Handling Multiple Exceptions in One Block

You can handle multiple exceptions in a single except block by using a tuple:

# Handling multiple exceptions in one block
try:
    x = int("abc")
    y = 10 / 0
except (ValueError, ZeroDivisionError) as e:
    print(f"An error occurred: {e}")

6

The finally Block

The finally block is always executed, regardless of whether an exception occurred. It’s typically used for cleanup actions:

# Using finally for cleanup
try:
    file = open("example.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("The file does not exist.")
finally:
    print("Closing the file.")

7

The else Block

The else block is executed if no exceptions occur in the try block:

# Using else to execute code if no exceptions occur
try:
    result = 10 / 2
except ZeroDivisionError:
    print("You cannot divide by zero.")
else:
    print(f"The result is {result}")

8

Logging Exceptions

Logging exceptions is a good practice for debugging and monitoring your applications:

# Logging exceptions
import logging

try:
    x = 10 / 0
except ZeroDivisionError as e:
    logging.error(f"An error occurred: {e}")

9

10

Common Mistakes with try, except, and finally

Here are some mistakes to avoid:

  • Not using specific exceptions in except blocks.
  • Ignoring exceptions without proper logging or handling.
  • Using finally blocks unnecessarily for actions handled by with statements.

11

What Did We Learn?

In this lesson, you learned:

  • How to use try and except blocks to handle exceptions.
  • How to use finally and else blocks for cleanup and additional logic.
  • The importance of logging exceptions for debugging.

Great job! Let’s move to the next topic.

Using try, except, and finally — illustration 11

Frequently asked questions

Is the “Using try, except, and finally” lesson free?

Yes — the full text of “Using try, except, and finally” is free to read here on the web, and the Learn AI with Python course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn AI with Python course, upgrade to CoddyKit PRO.

What will I learn in “Using try, except, and finally”?

Master error-handling blocks to catch and respond to exceptions. You practise Learn AI with Python with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Learn AI with Python?

No prior experience is required. Learn AI with Python on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Using try, except, and finally” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Learn AI with Python lesson?

Yes. Every Learn AI with Python lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Understanding Errors
  2. Using try, except, and finally
  3. Raising Exceptions
  4. Creating Custom Exceptions
← Back to Learn AI with Python