Exception Handling
Handle errors gracefully to prevent program crashes.
Try-Except Basics
try: number = int(input("Enter number: ")) result = 10 / number print(result) except: print("An error occurred!")
Specific Exceptions
try: number = int(input("Enter number: ")) result = 10 / number except ValueError: print("Invalid number!") except ZeroDivisionError: print("Cannot divide by zero!") except Exception as e: print(f"Error: {e}")
Try-Except-Else-Finally
try: file = open('data.txt', 'r') content = file.read() except FileNotFoundError: print("File not found!") else: print("File read successfully!") print(content) finally: print("Closing file...") try: file.close() except: pass
Raising Exceptions
def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero!") return a / b try: result = divide(10, 0) except ValueError as e: print(e)
Common Exceptions
| Exception | When It Occurs |
|---|---|
ValueError | Invalid value |
TypeError | Wrong type |
KeyError | Missing dict key |
IndexError | Invalid list index |
FileNotFoundError | File doesn't exist |
ZeroDivisionError | Division by zero |
Practice Exercises
- Handle file reading errors
- Validate user input with exceptions
- Create custom exceptions
- Use try-except with loops
- Build robust error handling
Next Lesson: Debugging