Programs don’t always run perfectly—sometimes things go wrong. For example, dividing by zero or trying to open a file that doesn’t exist can cause errors. If we don’t manage these errors, the whole program can crash.
Python gives us a way to catch these errors safely using a try and except block. This helps the program keep running, even when something unexpected happens.
💡 Analogy:
Think of a seatbelt in a car. It doesn’t stop accidents, but it protects you when one happens. Error handling doesn’t stop errors, but it stops your program from crashing.
By the end of this lesson, you will be able to:
✅ Understand what error handling is and why it’s important
✅ Use try and except blocks to catch and manage errors
✅ Handle different types of errors in Python
Error Handling – Catching and managing errors so the program doesn’t crash
Exception – An error during program execution (like ZeroDivisionError)
try block – Code that might cause an error
except block – Code that runs if an error happens
finally block – Code that always runs, even if there’s an error
Example 1: Basic Try-Except (General Error)
try:
user_input = input("Type something: ")
print("You typed:", user_input)
except:
print("Something went wrong.")
✅ What happens?
If the user types something normally → it prints it back.
If something unexpected goes wrong → the program doesn't crash. It prints a message.
Example 2: Handling Multiple Specific Errors
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: You can't divide by zero!")
except ValueError:
print("Error: Please enter only numbers.")
✅ What happens?
Valid numbers → the division is shown
Zero as second number → catches ZeroDivisionError
Text input → catches ValueError
Example 3: Using finally
try:
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("Error: The file does not exist.")
finally:
print("Closing program.")
✅ What happens?
If the file exists → it prints the content
If the file is missing → it prints an error message
The finally block always runs → prints "Closing program."
These are some of the most useful error types to know when using except.
🔗 Practice on W3Schools: Python Try-Except Tutorial – Learn how to handle different types of errors in Python. The total list of exceptions which are caught by the except block are listed here.
🔗 Try It Online: Run Your Code Here – Test your Python code instantly.
1️⃣ Basic Challenge:
Ask the user to input a number and convert their input into an integer using int().
Use a try and except block with ValueError to catch the error that is produced if they write "ten" instead of 10.
Print what they typed, or show "Something went wrong" if there’s an error.
2️⃣ Extended Challenge:
Ask the user for two numbers.
Divide the first by the second.
Use except ZeroDivisionError to catch the error produced if the second number is zero.
Write the example from this lesson on paper, ensuring you include:
✅ A try block with code that might cause an error.
✅ An except block that catches and handles errors.
✅ A finally block that runs regardless of what happens.
Read the example code before writing!