Advanced Python Tutorial 2: Exception Handling and Debugging
🎯 Introduction
In professional Python development, handling exceptions gracefully and using debugging tools effectively are critical skills. Let's master these essentials!
🚧 What Are Exceptions?
Exceptions are errors that disrupt the normal flow of a program. Python handles them using try-except
blocks.
try:
num = int(input("Enter a number: "))
result = 100 / num
print("Result:", result)
except ZeroDivisionError:
print("❌ Cannot divide by zero.")
except ValueError:
print("❌ Please enter a valid number.")
except Exception as e:
print(f"❌ Unexpected error: {e}")
🎭 Custom Exceptions
You can define your own exceptions for cleaner, domain-specific error handling.
class NegativeNumberError(Exception):
"""Custom exception for negative inputs."""
pass
def process_number(n):
if n < 0:
raise NegativeNumberError("Negative numbers are not allowed.")
return n * 2
try:
print(process_number(-5))
except NegativeNumberError as e:
print("❗ Error:", e)
"""Custom exception for negative inputs."""
pass
def process_number(n):
if n < 0:
raise NegativeNumberError("Negative numbers are not allowed.")
return n * 2
try:
print(process_number(-5))
except NegativeNumberError as e:
print("❗ Error:", e)
🕵️ Debugging with pdb
pdb
is Python’s built-in debugger. It allows stepping through code, inspecting variables, and identifying issues.
import pdb
def divide(a, b):
pdb.set_trace() # 🛑 Sets a breakpoint
return a / b
divide(10, 0)
def divide(a, b):
pdb.set_trace() # 🛑 Sets a breakpoint
return a / b
divide(10, 0)
📋 Best Practices
- ✅ Catch specific exceptions, not just
except:
. - ✅ Use
finally
for cleanup (closing files, DB connections). - ✅ Log exceptions using Python’s
logging
module in real applications.
🔎 SEO and AdSense Tips
- Use headings and semantic tags.
- Target keywords like “python debugging tutorial”.
- Ensure mobile responsiveness and fast load times.
✅ Summary
- Mastered
try-except
structure. - Learned to build custom exceptions.
- Used
pdb
for step-by-step debugging.
Keep practicing to become confident with exception handling in real-world Python apps!
Comments
Post a Comment