Error Handling
Introduction to Error Handling
Errors are inevitable in programming. Files might not exist, users might enter invalid data, or network connections might fail. Error handling allows your program to gracefully handle these situations instead of crashing.
Python uses exceptions to handle errors. When an error occurs, Python raises an exception, which can be caught and handled by your code.
Common Errors
Here are some common errors you'll encounter:
common_errors.py
# FileNotFoundError - file doesn't exist
open("nonexistent.txt", "r") # Raises FileNotFoundError
# ValueError - invalid value
int("abc") # Raises ValueError
# KeyError - key doesn't exist in dictionary
my_dict = {"a": 1}
my_dict["b"] # Raises KeyError
# IndexError - index out of range
my_list = [1, 2, 3]
my_list[10] # Raises IndexError
# ZeroDivisionError - division by zero
10 / 0 # Raises ZeroDivisionError
Why Handle Errors?
Error handling is important because:
- Prevents crashes - Your program continues running
- Better user experience - Shows helpful error messages
- Data integrity - Prevents data loss or corruption
- Debugging - Easier to find and fix issues
- Robustness - Program handles unexpected situations
Basic Error Handling
Use try and except blocks to handle errors:
basic_handling.py
# Basic try-except
try:
result = 10 / 0
print(result)
except ZeroDivisionError:
print("Cannot divide by zero!")
# Handling file errors
try:
with open("data.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found!")
print("Program continues...")
Best Practices
✅ Error Handling Tips
• Always handle errors that might occur
• Be specific about which errors to catch
• Provide helpful error messages to users
• Don't catch all errors blindly - let unexpected errors show
• Use error handling for file operations, user input, and network calls
main.py
📤 Output
Click "Run" to execute...