← All lessons

Lesson 08

Errors & Exceptions

When Python cannot complete an operation, it raises an exception and stops the program.

A try block contains code that might fail. An except block handles a specific failure.

Catch specific exceptions such as ValueError rather than hiding every possible error.

text = "42"

try:
    number = int(text)
    print(number * 2)
except ValueError:
    print("Please enter a whole number.")

Check your understanding

What exception does int("oops") raise?

CHALLENGE

Try converting "oops" to an int. Catch ValueError and print Invalid number.

Practice →
Next: List Comprehensions →