Lesson 33 of 4083%

(Progress persistence is disabled until Phase 9)

Python
Intermediate

Exceptions and Error Handling

Prevent your programs from crashing when things go wrong.

Exceptions and Error Handling

What You’ll Learn

You’ll learn how to handle errors gracefully using try...except blocks.

The Problem

When an error (exception) occurs, Python will normally stop and generate an error message. This crashes your program.

print(10 / 0) # ZeroDivisionError! Crash!
print("This line will never run.")

try…except

The try block lets you test a block of code for errors. The except block lets you handle the error.

try:
    print(10 / 0)
except:
    print("An error occurred! Cannot divide by zero.")

print("The program continues...")

Catching Specific Errors

You can specify which kind of error you want to catch.

try:
    print(x) # x is not defined
except NameError:
    print("Variable x is not defined")
except:
    print("Something else went wrong")

The finally Block

The finally block, if specified, will be executed regardless of whether the try block raises an error or not. Useful for closing files or database connections.

try:
    print(10 / 2)
except:
    print("Error")
finally:
    print("Finished checking")

Lesson Progress

Take QuizBuild a Python Project