Python Advanced: Error Handling (try / except)

Level Goal

Today you will learn:

By the end, you will be able to write programs that don’t crash when the user enters wrong input.

Step 1: Why Error Handling is Important

Programs crash if they get unexpected input:

Example without error handling:


number = int(input("Enter a number: "))
print(10 / number)

Problem:

Step 2: Using try / except

try → code block that might cause errors
except → what happens when a specific error occurs


try:
    number = int(input("Enter a number: "))
    print(10 / number)
except ValueError:
    print("Please enter a number!")
except ZeroDivisionError:
    print("Division by zero is not allowed!")

Explanation:

Step 3: General Error Handling

You can also catch all errors if you don’t know the exact error type:


try:
    # code
except:
    print("An error occurred!")

Tip:

Step 4: Practical – Number Guessing Game

We improve the number guessing game from Day 7:

Problem before:


guess = int(input("Guess the number from 1 to 10: "))

With error handling:


import random

number = random.randint(1, 10)
guess = 0
attempts = 0

while guess != number:
    try:
        guess = int(input("Guess the number from 1 to 10: "))
        attempts += 1
        if guess < number:
            print("Too low!")
        elif guess > number:
            print("Too high!")
        else:
            print("Correct! You took", attempts, "attempts!")
    except ValueError:
        print("Please enter a number!")

Explanation:

Practice Exercise

Enhance your existing number guessing game: