๐ Lesson 23: Python Exception Handling – Try, Except & Custom Errors
Welcome to Lesson 23! Today we’ll explore exception handling in Python. Exceptions are errors that occur during program execution, and handling them ensures your program doesn’t crash unexpectedly. Mastering exception handling will make your programs more robust and user-friendly.
⭐ What You Will Learn in This Lesson
- How to use
tryandexceptto handle errors - Manage multiple exceptions and prevent program crashes
- Use
elseandfinallyto enhance exception handling - How to raise custom exceptions for better error handling
๐ฅ Who Is This Lesson For?
- Python developers who want to improve error handling in their code
- Anyone building robust applications that require user input validation
- Developers interested in making their code more fault-tolerant and user-friendly
๐ฆ 1. Basic Try & Except
Start by handling simple errors using try and except:
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Oops! That’s not a valid number.")
๐ฆ 2. Handling Multiple Exceptions
You can handle multiple exceptions by chaining except blocks:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid value!")
๐ฆ 3. Using Else & Finally
else runs if no exception occurs, while finally always runs regardless of errors:
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
else:
print("Success! You entered:", num)
finally:
print("This always runs.")
๐ฆ 4. Raising Exceptions
You can raise custom exceptions with the raise statement:
age = -5
if age < 0:
raise ValueError("Age cannot be negative!")
๐ฆ 5. Custom Exception Classes
For more control, create custom exception classes to handle specific errors:
class NegativeAgeError(Exception):
pass
age = -10
try:
if age < 0:
raise NegativeAgeError("Age cannot be negative!")
except NegativeAgeError as e:
print("Error:", e)
๐งฉ 6. Why Exception Handling Matters
- Prevents program crashes
- Helps debug and log errors
- Makes code robust and user-friendly
- Essential for real-world applications and APIs
๐งช Practice
- Write a program that divides two numbers and handles division by zero.
- Prompt for an integer input and handle invalid entries.
- Create a custom exception for invalid email format and raise it.
- Use
finallyto print a goodbye message in a program.
❌ Common Mistakes
- Not catching the correct exception
- Forgetting to raise custom exceptions when necessary
- Misusing the
elseandfinallyblocks
❓ Frequently Asked Questions (FAQ)
1. What is the difference between except and finally?
except handles errors, while finally ensures that the code in it will always run, regardless of whether an exception occurs or not.
2. Why should I use custom exceptions?
Custom exceptions provide more meaningful error messages and allow you to handle specific errors more effectively.
3. Can I use else without finally?
Yes! The else block can be used without finally. It runs only if no exceptions were raised in the try block.
๐ What’s Next?
In the next lesson, you’ll learn about:
- Context Managers and how to manage resources like files and connections
- Understanding the
withstatement for resource management - How to write cleaner code with automatic cleanup
Comments
Post a Comment