Introduction
Python uses exceptions to handle errors gracefully and prevent program crashes.
Try-Except Block
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"Error: {e}")
else:
print("No errors occurred")
finally:
print("This always runs")
Raising Exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Invalid age")
return True
Custom Exceptions
class InvalidInputError(Exception):
def __init__(self, message="Invalid input"):
self.message = message
super().__init__(self.message)
raise InvalidInputError("Input must be positive")
Common Exceptions
| Exception | Description |
|---|---|
TypeError | Operation on incompatible types |
ValueError | Invalid value for operation |
IndexError | List index out of range |
KeyError | Dictionary key not found |
FileNotFoundError | File doesn't exist |
Practice Problems
- Create a safe calculator that handles division by zero
- Implement input validation with custom exceptions
- Parse user input and handle all possible errors
- Create a retry mechanism for failing operations
- Build error logging system