๐ Lesson 13: Python Exception Handling – Handle Errors Like a Pro
Welcome to Lesson 13! Today we’ll learn about exception handling in Python. Programs often encounter errors, and exception handling lets your code respond without crashing.
⭐ What You Will Learn in This Lesson
- Understand what exceptions are in Python
- Use
try,except,else, andfinally - Handle different types of errors
- Keep your programs running smoothly
- Improve debugging and user experience
๐ฅ Who Is This Lesson For?
- Beginners who want to write robust Python code
- Anyone learning to handle runtime errors safely
- Students building real-world applications or scripts
⚡ What Are Exceptions?
Exceptions are errors that occur during program execution. Examples include:
- Dividing by zero
- Accessing an index that doesn’t exist
- Opening a file that doesn’t exist
๐งฉ 1. Using try and except
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Invalid input! Please enter a number.")
๐งฉ 2. Using else and finally
else: runs if no error occurs. finally: always runs, even if an error occurs.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
else:
print("Division successful:", result)
finally:
print("This always runs!")
๐งฉ 3. Why Exception Handling Matters
- Keeps programs running instead of crashing
- Helps debug errors more easily
- Improves user experience
- Essential for real-world applications
๐งช Practice
- Ask the user for two numbers and divide them. Handle division by zero.
- Ask the user to enter a number and handle invalid input (non-integer).
- Write a program that tries to open a file and handles the error if the file doesn’t exist.
- Use
elseandfinallyin a small program to see their behavior. - Create a program that handles multiple types of exceptions and prints a friendly message for each.
Bonus: Experiment with different built-in exception types like
IndexError, KeyError, FileNotFoundError to see how Python reacts.
❌ Common Mistakes
- Not using
tryfor code that can fail - Using a generic
exceptwithout specifying the error type - Forgetting that
finallyalways executes
❓ Frequently Asked Questions (FAQ)
1. Can I catch multiple exceptions in one block?
Yes. Example: except (ValueError, ZeroDivisionError):
2. What happens if no exception occurs?
The else block executes if present.
3. Do I have to use finally?
No, but it is useful for cleanup actions like closing files.
๐ What’s Next?
In the next lesson, you’ll learn about:
- Organizing code using Python modules and packages
- Importing built-in and custom modules
- Structuring larger Python projects
Comments
Post a Comment