► Understanding Debugging and Error Handling
Debugging is the process of finding and fixing errors in your code. Error handling is anticipating problems and writing code to deal with them gracefully. Both skills are essential for writing robust programs.
► Real-World Analogy
Think of debugging like being a detective:
» Errors are clues that something went wrong
» Print statements are like interviewing witnesses
» Debugger tools let you examine the crime scene frame by frame
» Error handling is like having a backup plan
» Logs are your case notes for future reference
► Key Concepts
✓ Syntax errors: Typos and grammar mistakes
✓ Runtime errors: Problems during execution
✓ Logic errors: Code runs but produces wrong results
✓ Try-except blocks: Catch and handle exceptions
✓ Debug prints: Output values to track program flow
■ Code Examples
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# Try-except for error handling try: number = int(input("Enter a number: ")) result = 10 / number print(f"Result: {result}") except ValueError: print("Error: Please enter a valid number") except ZeroDivisionError: print("Error: Cannot divide by zero") except Exception as e: print(f"Unexpected error: {e}") finally: print("Execution completed") # Debug prints def calculate_average(numbers): print(f"Debug: Input = {numbers}") total = sum(numbers) print(f"Debug: Total = {total}") avg = total / len(numbers) print(f"Debug: Average = {avg}") return avg # Using assertions def divide(a, b): assert b != 0, "Divisor cannot be zero" return a / b |
