← Python from Scratch Lesson 49 of 78 · 10 XP

Handling errors: try / except

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

When something goes wrong, Python raises an exception and the program crashes. With try / except you can catch it and handle it:

try:
    n = int(input())
    print(100 / n)
except ValueError:
    print("Please enter a number")
except ZeroDivisionError:
    print("You can't divide by zero")

The full form:

try:
    ...            # code where an error may happen
except ValueError as e:
    print("Error:", e)       # e is the error object itself, with a description
else:
    ...            # runs if there was NO error
finally:
    ...            # runs ALWAYS (for example, to close a file)

Catch specific errors, not everything at once. A bare except: also hides the errors you'd want to know about.

You can raise your own error with raise:

if age < 0:
    raise ValueError("Age can't be negative")

Task. Read two lines and print the result of dividing the first number by the second, rounded to 2 decimal places. If something other than a number is entered, print Numbers required. If the divisor is zero, print You can't divide by zero.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.