MyMisPal
← Python lessons
Lesson 11 of 13

Errors and try / except

When an error happens at runtime, Python stops the program. try and except let you handle it instead of crashing.

PYTHON
try:
    qty = int("ten")
except ValueError:
    print("Please enter a number")
typo (missing bracket or :)SyntaxError
undefined nameNameError
wrong type for the operationTypeError
unsuitable valueValueError
list index out of rangeIndexError
missing dictionary keyKeyError
division by zeroZeroDivisionError
PYTHON
def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return None

print(safe_divide(10, 2))
print(safe_divide(10, 0))
PYTHON
prices = {"Laptop": 4800}
try:
    print(prices["Phone"])
except KeyError as e:
    print("Missing product:", e)
finally:
    print("Lookup finished")

Exercises

Exercise 1

Read a value. If it's a whole number print it doubled, otherwise print invalid.

Exercise 2

You have values = ["10", "x", "30", "", "5"]. Add up only the valid numbers, skipping the rest with try/except, and print the total.

Spotted a mistake on this page, or have an idea to improve the site?