0PricingLogin
Learn AI with Python · Lesson

Using try, except, and finally

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

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

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