Welcome to Day 18 of the 100 Days of Python series!
Today we tackle a critical skill for writing robust and error-resistant Python programs — Exception Handling using try
, except
, and more.
We all make mistakes — and so does code. Instead of letting programs crash, Python gives us tools to catch and handle errors gracefully.
Let’s dive in. 🐍
📦 What You’ll Learn
- What exceptions are and how they happen
- How to use
try
andexcept
blocks - Optional tools:
else
andfinally
- How to handle multiple exceptions
- Real-world examples
⚠️ What Is an Exception?
An exception is a runtime error that interrupts the normal flow of a program. Common examples include:
- Dividing by zero
- Accessing an invalid index
- Converting a string to a number improperly
- File not found
Without Handling:
num = int(input("Enter a number: "))
print(10 / num)
If the user enters 0 or a string, the program crashes. Let's fix that.
✅ Basic try-except
Block
try:
num = int(input("Enter a number: "))
result = 10 / num
print(result)
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Please enter a valid number.")
🔍 Output examples:
- Input:
0
→ "You can't divide by zero!" - Input:
"abc"
→ "Please enter a valid number."
🧪 Catching All Exceptions (Not Recommended Often)
try:
risky_code()
except Exception as e:
print("Something went wrong:", e)
Useful for logging or debugging, but try to handle specific exceptions when possible.
🧠 Using else
and finally
-
else
runs if no exception occurs -
finally
runs no matter what (great for cleanup)
try:
num = int(input("Enter number: "))
result = 10 / num
except ZeroDivisionError:
print("Can't divide by zero.")
else:
print("Division successful:", result)
finally:
print("This always runs.")
🔁 Handling Multiple Errors
try:
numbers = [1, 2, 3]
print(numbers[5]) # IndexError
except (IndexError, ValueError) as e:
print("An error occurred:", e)
🚀 Real-World Example: Safe User Input
def get_age():
try:
age = int(input("Enter your age: "))
print("You are", age, "years old.")
except ValueError:
print("Invalid age. Please enter a number.")
get_age()
🧰 Custom Exceptions (Advanced)
You can define your own exceptions for specific business logic:
class AgeTooLowError(Exception):
pass
def check_age(age):
if age < 18:
raise AgeTooLowError("You must be at least 18.")
🧼 Best Practices
- ✅ Catch specific exceptions (
ValueError
,ZeroDivisionError
) - ✅ Use
finally
for cleanup (e.g., closing files) - ✅ Avoid bare
except:
unless absolutely necessary - ✅ Log or display meaningful error messages
- 🚫 Don’t use exceptions for normal control flow
🧠 Recap
Today you learned:
- What exceptions are
- How to use
try
,except
,else
, andfinally
- How to handle multiple and custom exceptions
- Real-world examples to make your programs crash-resistant