Lesson 28 of 34

try / except: Handling Errors

9 min 30 XP

If a user types letters instead of a number, int() raises a ValueError and the program stops. Put risky code in try and handle the problem in except.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

Write a separate except for each kind of error. The finally part always runs.

Example: edit me and press Run

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.

You can raise your own errors: raise ValueError("Age cannot be negative")

Challenge

+30 XP

Read a value with input(). If it is a whole number, print double the number. Otherwise print Invalid. Use try / except.

Output Loading Python (first time takes a few seconds)
Press Run to see the result here.