🛡️ Error Handling
Error handling is crucial for building robust Python applications. Python provides powerful tools to catch, handle, and recover from errors gracefully, preventing crashes and providing meaningful feedback to users.
# Basic error handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
result = 0
print(f"Result: {result}")
# Multiple exception types
try:
number = int("abc")
except ValueError:
print("Invalid number format")
except Exception as e:
print(f"Unexpected error: {e}")
🎯 Why Error Handling Matters
Proper error handling helps you:
- Prevent Crashes 💥: Keep applications running
- User Experience 😊: Provide helpful error messages
- Debugging 🔍: Identify and fix issues quickly
- Data Safety 🔒: Protect against corruption
- Maintenance 🔧: Build reliable, maintainable code
📚 Error Handling Topics
Master Python's error handling capabilities:
- 🚨 Handle Exceptions Learn try/except blocks and exception handling patterns.
- ⚡ Create Custom Exceptions Build your own exception classes for specific error cases.
- 🔍 Debug Code Use debugging tools and techniques to find and fix issues.
- 📝 Use Logging Implement logging for tracking errors and application behavior.
- 🔄 Implement Retry Logic Add resilience with automatic retry mechanisms.
📊 Exception Reference Tables
Common Built-in Exceptions
Exception | When It Occurs | Example |
---|---|---|
ValueError | Invalid value for operation | int("abc") |
TypeError | Wrong data type | "text" + 5 |
KeyError | Dictionary key not found | dict["missing_key"] |
IndexError | List index out of range | list[100] |
FileNotFoundError | File doesn't exist | open("missing.txt") |
ZeroDivisionError | Division by zero | 10 / 0 |
AttributeError | Object has no attribute | "text".missing_method() |
ImportError | Module import fails | import nonexistent |
Exception Handling Patterns
Pattern | Use Case | Example |
---|---|---|
Basic try/except | Handle single exception | except ValueError: |
Multiple except | Handle different errors | except (ValueError, TypeError): |
Catch all | Handle any exception | except Exception: |
Exception info | Get error details | except Exception as e: |
Finally block | Always execute cleanup | finally: |
Else block | Run if no exceptions | else: |
🌟 Quick Examples
Here's what you'll learn to handle:
# File handling with errors
try:
with open("data.txt", "r") as file:
content = file.read()
print("File read successfully")
except FileNotFoundError:
print("File not found")
except PermissionError:
print("No permission to read file")
# Data conversion with errors
try:
user_input = "25"
age = int(user_input)
print(f"Age: {age}")
except ValueError:
print("Please enter a valid number")
# Custom error handling
class CustomError(Exception):
pass
try:
raise CustomError("Something went wrong")
except CustomError as e:
print(f"Custom error: {e}")
🏗️ Error Handling Hierarchy
Understanding Python's exception hierarchy helps you catch errors effectively:
BaseException
+-- Exception
+-- ValueError
+-- TypeError
+-- KeyError
+-- IndexError
+-- FileNotFoundError
+-- ZeroDivisionError
+-- AttributeError
+-- ImportError
Build robust Python applications that handle errors gracefully! 🛡️✨
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.