Day 10: Error Handling in Python
Goal: Master Python’s error handling using try, except, else, and finally blocks. Learn to create custom exceptions and debug code effectively.
1. What Are Errors and Exceptions?
Syntax Errors: Caused by incorrect code structure (e.g., missing colon or parenthesis).
if x > 5 # SyntaxError: Missing colon Exceptions: Errors detected during execution (e.g., dividing by zero or accessing invalid keys).
print(10 / 0) # ZeroDivisionError 2. The try-except Block
Basic Syntax
try:
# Code that might raise an error
except ErrorType:
# Code to handle the error Example:
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input! Please enter a valid integer.") 3. Handling Multiple Exceptions
Specific Exceptions
Catch different errors with multiple except blocks:
try:
x = 10 / int(input("Enter a non-zero number: "))
print(my_dict["invalid_key"])
except ZeroDivisionError:
print("Cannot divide by zero!")
except KeyError:
print("Key not found in dictionary!") Catch All Exceptions (Not Recommended)
Use sparingly to avoid hiding bugs:
try:
# Risky code
except Exception as e:
print(f"An error occurred: {e}") 4. The else Clause
Runs only if no exceptions occur.
Useful for code that depends on the
tryblock succeeding.
try:
result = 10 / int(input("Enter a number: "))
except ZeroDivisionError:
print("Division by zero!")
else:
print(f"Result: {result}") # Executed only if no error 5. The finally Clause
Runs regardless of whether an exception occurred.
Use for cleanup tasks (e.g., closing files or database connections).
file = None
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
if file:
file.close() # Always executes 6. Built-in Exceptions
7. Raising Exceptions
Force an error with raise to enforce constraints:
def calculate_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
return age
try:
calculate_age(-5)
except ValueError as e:
print(e) # Output: Age cannot be negative! 8. Custom Exceptions
Create your own exceptions for specific use cases:
class InvalidEmailError(Exception):
"""Raised when an email format is invalid."""
def validate_email(email):
if "@" not in email:
raise InvalidEmailError(f"{email} is invalid!")
try:
validate_email("alice.example.com")
except InvalidEmailError as e:
print(e) 9. Logging Errors
Use the logging module to log errors (better than print() for debugging):
import logging
logging.basicConfig(filename="errors.log", level=logging.ERROR)
try:
10 / 0
except ZeroDivisionError:
logging.error("Division by zero attempted!", exc_info=True) 10. Best Practices
Be Specific: Catch specific exceptions (avoid bare
except:).Use
finallyfor Cleanup: Ensure resources (files, network connections) are released.Log Errors: Use
loggingto track issues in production.Fail Early: Validate inputs at the start of functions.
Real-World Example: AI/ML Context
Handle errors when loading datasets:
try:
import pandas as pd
df = pd.read_csv("dataset.csv")
except FileNotFoundError:
print("Dataset not found! Check the file path.")
except pd.errors.EmptyDataError:
print("The dataset is empty!")
except Exception as e:
print(f"Unexpected error: {e}") Practice Exercise
Write a function that divides two numbers but raises a
ValueErrorif either is not a number.Create a custom exception
InvalidInputErrorfor non-numeric inputs.Use
try-exceptto handle file I/O and custom errors.
Solution:
class InvalidInputError(Exception):
pass
def divide(a, b):
try:
if not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
raise InvalidInputError("Non-numeric input!")
return a / b
except ZeroDivisionError:
return "Cannot divide by zero!"
try:
print(divide(10, "2"))
except InvalidInputError as e:
print(e) Key Takeaways
try-except: Gracefully handle runtime errors.Custom Exceptions: Improve code readability for domain-specific errors.
Logging: Critical for debugging production code.
What’s Next?
Day 11 introduces NumPy, the backbone of numerical computing in Python. You’ll use it for vectorized operations in AI/ML!
By mastering error handling today, you’ll write robust, crash-resistant code—essential for real-world AI/ML pipelines! 🛠️



