Exception Handling: Making Your Code Error-Proof!
Imagine you’re playing a video game and suddenly hit a wall because you made the wrong move. The game doesn’t crash—it shows a message like, “Oops, wrong way!” and lets you try again. That’s what exception handling does in Python! It helps your program deal with unexpected situations without crashing.
Let’s dive in and learn how to handle these “oops moments” in Python!
🛑 What are Exceptions?
An exception is like an error that stops your program when something unexpected happens. For example:
- Dividing by zero (oops, math doesn’t like that!).
- Trying to open a file that doesn’t exist (oops, where’s that file?).
- Typing something unexpected, like words instead of numbers (oops, mismatch!).
🛠️ How Do We Handle Exceptions?
Python gives us a magic tool called try
and except
. Here’s the basic idea:
- Try: Tell Python to try running a piece of code.
- Except: Catch any error and decide what to do instead of crashing.
Example: Catching an Error
try:
number = int(input("Enter a number: "))
print("You entered:", number)
except ValueError:
print("Oops! That's not a number.")
How it Works:
- Python tries to turn your input into a number.
- If you type something that’s not a number, Python catches the error and runs the
except
part.
🚧 Common Exception Types
Here are a few common errors Python can handle:
Exception | When It Happens |
---|---|
ZeroDivisionError | Dividing a number by zero. |
ValueError | Using the wrong value type. |
FileNotFoundError | Trying to open a file that doesn’t exist. |
KeyError | Looking for a key in a dictionary that’s not there. |
🎯 Handling Multiple Exceptions
Sometimes, different things can go wrong. You can handle them all separately.
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
print("Result is:", result)
except ZeroDivisionError:
print("Oops! You can’t divide by zero.")
except ValueError:
print("Oops! Please enter valid numbers.")
What Happens:
- If you divide by zero, the program says, “Oops! You can’t divide by zero.”
- If you type something other than a number, it says, “Oops! Please enter valid numbers.”
🧹 Finally: Cleaning Up!
The finally
block lets you run code no matter what happens—whether there’s an error or not.
try:
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("Oops! File not found.")
finally:
print("Finished trying to read the file.")
🌟 Raising Your Own Exceptions
Sometimes, you want to create your own “oops moments.” Use raise
to throw an exception.
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age can’t be negative!")
else:
print("Your age is:", age)
🏋️♂️ Practice Questions
1. Catch a Division Error
Write a program that asks the user to divide two numbers and handles a division by zero error.
Solution:
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Oops! Denominator can’t be zero.")
2. File Not Found
Write a program that tries to open a file and catches the error if the file doesn’t exist.
Solution:
try:
file = open("nonexistent_file.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("Oops! File doesn’t exist.")
3. Raise Your Own Error
Write a program that raises an exception if someone enters an invalid age.
Solution:
try:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age can’t be negative!")
else:
print("Your age is:", age)
except ValueError as e:
print("Error:", e)