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
Top comments (0)