0% found this document useful (0 votes)
9 views10 pages

Python Error Handling & Debugging Guide

This document provides guidance on error handling and debugging in Python, emphasizing the importance of graceful error management to enhance user experience and application reliability. It covers common error types, the use of try-except blocks, raising custom exceptions, and best practices for effective debugging. Key takeaways include the importance of specific exception handling and systematic debugging techniques to improve code quality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views10 pages

Python Error Handling & Debugging Guide

This document provides guidance on error handling and debugging in Python, emphasizing the importance of graceful error management to enhance user experience and application reliability. It covers common error types, the use of try-except blocks, raising custom exceptions, and best practices for effective debugging. Key takeaways include the importance of specific exception handling and systematic debugging techniques to improve code quality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Error Handling & Debugging

in Python
Master the art of writing bulletproof code that gracefully handles errors and
helps you find bugs faster.
Why Error Handling Matters
The Problem
Without proper error handling, a single unexpected input can crash
your entire program. Users see cryptic messages, lose their work, and
your application's reputation suffers.

Professional code anticipates problems and handles them gracefully,


providing clear feedback when things go wrong.
Common Python Error Types

SyntaxError TypeError
Invalid Python syntax. Missing colons, unmatched Operation on incompatible types. Like trying to add a string
parentheses, or incorrect indentation. Python can't even run and integer, or calling a non-function.
your code.

ValueError IndexError
Right type, wrong value. Converting "abc" to integer, or Accessing a list or string position that doesn't exist. Attempting
unpacking the wrong number of values. index 5 on a 3-item list.
The Try-Except Block
The try-except block is your safety net, catching errors before they crash your
program and allowing you to respond gracefully.

try:
user_age = int(input("Enter your age: "))
print(f"Next year you'll be {user_age + 1}")
except ValueError:
print("Please enter a valid number for age.")
except KeyboardInterrupt:
print("\nOperation cancelled by user.")

The code in the try block runs normally. If an error occurs, Python jumps to
the matching except block instead of crashing.
Adding Finally for Cleanup
Try Block Executes
Your main code runs here. This is where errors might occur.

Except Handles Errors


If an error occurs, jump here to handle it gracefully.

Finally Always Runs


Cleanup code here runs no matter what—success, error, or return statement.

try:
file = open("[Link]", "r")
process_data([Link]())
except FileNotFoundError:
print("File not found!")
finally:
[Link]() # Always closes, preventing resource leaks
Raising Your Own Exceptions
Use raise to create custom error messages that help users understand what went wrong
and how to fix it.

def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age seems unrealistic")
return age

try:
user_age = set_age(-5)
except ValueError as e:
print(f"Error: {e}")

Custom exceptions make your code self-documenting and provide clear feedback about
invalid inputs or states.
Error Handling Best Practices

Be Specific Fail Fast


Catch specific exceptions like ValueError or Don't silence errors that indicate real problems. Let them
FileNotFoundError, not bare except: which hides surface during development so you can fix root causes.
bugs.

Provide Context Log Exceptions


Include helpful error messages that tell users what went In production code, log exceptions with timestamps and
wrong and suggest how to fix it. context so you can diagnose issues later.

Warning: Avoid except Exception: or bare except: in most cases—they catch everything, including keyboard interrupts
and system exits, making debugging nearly impossible.
Debugging with Print Statements

The humble print() function is your first debugging tool. Strategic print statements help
you trace program flow and inspect variable values.

def calculate_discount(price, discount_percent):


print(f"DEBUG: price={price}, discount={discount_percent}")

discount_amount = price * (discount_percent / 100)


print(f"DEBUG: discount_amount={discount_amount}")

final_price = price - discount_amount


print(f"DEBUG: final_price={final_price}")

return final_price

Pro tip: Add prefixes like "DEBUG:" to make these statements easy to find and remove
later.
Level Up: Python Debugger (PDB)
01 02

Insert Breakpoint Inspect Variables


Add import pdb; pdb.set_trace() or breakpoint() where you When code pauses, type variable names to see their values. Use pp
want to pause execution. variable for pretty-print.

03 04

Step Through Code Test Fixes


Commands: n (next line), s (step into), c (continue), l (list code), q (quit). Execute code interactively in the debugger to test solutions before modifying
your actual code.
Key Takeaways
Handle Errors Gracefully Raise Meaningful Exceptions
Use try-except blocks to catch specific exceptions and Create custom error messages with raise to guide users
provide helpful feedback instead of letting your program when they provide invalid input or encounter edge cases.
crash.

Debug Systematically Be Specific, Not Generic


Start with print statements for quick checks, then graduate Catch specific exceptions, avoid bare excepts, and let real
to PDB for complex issues requiring step-by-step bugs surface during development so you can fix them
inspection. properly.

With solid error handling and debugging skills, you'll write more reliable code and spend less time hunting mysterious bugs.

You might also like