Catch Bugs, Avoid Crashes, and Write Reliable Code
Even the best-written code can face unexpected situations β wrong input, missing files, or network issues. Thatβs where error handling comes in. Instead of crashing, your program can handle the error gracefully and keep going.
π« 1. Types of Errors in Python #
πΉ Syntax Errors #
Happen when Python canβt parse your code.
print("Hello" # Missing closing parenthesis
πΉ Runtime Errors (Exceptions) #
Happen while the program is running.
x = 10 / 0 # ZeroDivisionError
π‘ 2. Using try
, except
Blocks #
Wrap risky code inside a try
block and handle potential errors with except
.
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("β Cannot divide by zero.")
except ValueError:
print("β Please enter a valid number.")
π 3. else
and finally
in Try Blocks #
β
else
: Runs if no exception occurs #
π finally
: Always runs (good for cleanup) #
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("β File not found!")
else:
print("π File read successfully.")
finally:
print("π Closing file (if opened).")
try:
file.close()
except:
pass
π§ 4. Raising Your Own Exceptions #
Sometimes you need to create your own error messages.
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative!")
π§° 5. Debugging Tools in Python #
π§ͺ Using print()
for Debugging (Old School but Effective) #
x = 5
y = 0
print("Debug: x =", x, " y =", y)
print(x / y) # You'll catch it before crash
π Using pdb
(Python Debugger) #
import pdb
pdb.set_trace() # Execution will pause here
x = 10
y = 5
z = x + y
print(z)
Use commands like:
n
: next linec
: continueq
: quit
β οΈ Common Exceptions #
Exception | Trigger Example |
---|---|
ZeroDivisionError | Division by zero |
ValueError | Converting string to int (int("abc") ) |
FileNotFoundError | Opening non-existent file |
TypeError | Adding string to integer |
KeyError | Accessing missing dictionary key |
π§ Real-World Use Case: Login Authenticator with Error Handling #
Letβs create a CLI app that:
- Takes username and password
- Handles incorrect input
- Locks out after 3 failed attempts
β Code Example #
def login_system():
correct_username = "admin"
correct_password = "1234"
attempts = 3
while attempts > 0:
try:
username = input("Username: ")
password = input("Password: ")
if not username or not password:
raise ValueError("Fields cannot be empty!")
if username == correct_username and password == correct_password:
print("β
Login successful!")
return
else:
attempts -= 1
print(f"β Invalid credentials. Attempts left: {attempts}")
except ValueError as e:
print("β οΈ", e)
print("π« Too many failed attempts. Account locked.")
# Run it
login_system()
π₯ Output Example #
Username: admin
Password: wrong
β Invalid credentials. Attempts left: 2
Username:
Password: 1234
β οΈ Fields cannot be empty!
Username: admin
Password: 1234
β
Login successful!
π Key Takeaways #
Feature | Purpose |
---|---|
try...except | Catch and handle runtime errors |
finally | Cleanup, like closing files |
raise | Manually trigger exceptions |
pdb | Step-by-step code investigation |
Best Practice | Always validate user inputs |
π Wrap Up #
You can’t predict every problem your code may face β but you can plan how it responds to them. Error handling makes your apps smarter, safer, and way more user-friendly.
π Up Next: #
Modules & Code Organization
Learn how to break your code into reusable modules, import them smartly, and manage larger projects easily β with a Library Book Management App example.