Error Handling in Python
Part 1: What Are Errors?
Introduction
Imagine you're baking a cake and the recipe says "Add 2 cups of flour." What could go wrong?
• You might grab salt instead of sugar (wrong ingredient)
• You might add too much flour (wrong amount)
• You might forget to turn on the oven (missed step)
Programming is the same way. Things can go wrong, and we need to be prepared. Error handling is not
about preventing mistakes—it's about managing them gracefully when they occur.
Why Error Handling Matters
• Logic Errors - Code runs but produces incorrect results
Two Primary Error Handling Techniques
◦ Conditionals (if-else) - Use when you can check conditions beforehand
◦ Exception Handling (try-except) - Use when errors are difficult to predict
The Golden Rule
"Always anticipate what could go wrong, then implement appropriate safeguards."
Professional Mindset
Encountering errors does not indicate poor programming skills. Handling them effectively demonstrates
professionalism and technical competence.
Next Steps
To solidify your understanding of error handling:
1. Complete the practice exercises above
2. Review your previous programs and add error handling
3. Test all programs with invalid and unexpected inputs
4. Study how error handling is implemented in professional code examples
5. Remember that thorough error handling is a mark of quality software
Error handling is not just about preventing crashes—it's about creating robust, user-friendly programs
that behave predictably even when faced with unexpected situations.
Programming 1 | Error Handling Complete Guide
Remember: Good programmers write code that works. Great programmers write code that handles failures
gracefully.
User Experience: Programs should not crash unexpectedly
• Debugging: Good error messages help identify problems quickly
• Professionalism: Production code must handle edge cases
• Reliability: Programs should continue running even when users provide unexpected input
Part 2: The Three Types of Errors
1. Syntax Errors - "Typos in Your Code"
These are mistakes in the Python language itself. Python cannot even run your code because it doesn't
understand what you wrote.
Example 1: Missing Colon
age = 18
if age >= 18
print("You can vote")
Error: SyntaxError: invalid syntax
Fix: Add a colon after the if statement
age = 18
if age >= 18:
print("You can vote")
Example 2: Missing Quote
name = "Alice
print(name)
Error: SyntaxError: unterminated string literal
Fix: Close the quote
name = "Alice"
print(name)
Key Point: Syntax errors stop your program before it even starts running. The Python interpreter cannot
understand your code.
2. Runtime Errors - "Crashes While Running"
Your code has correct syntax, but something goes wrong during execution. These errors only appear when
the problematic line of code is actually executed.
Example 1: Division by Zero
number = 10
divisor = 0
result = number / divisor # Program crashes here
print(result)
Error: ZeroDivisionError: division by zero
Example 2: Type Mismatch
age = "twenty"
next_year = age + 1 # Cannot add integer to string
print(next_year)
Error: TypeError: can only concatenate str (not "int") to str
Example 3: Invalid Conversion
user_input = "hello"
number = int(user_input) # Cannot convert "hello" to integer
print(number)
Error: ValueError: invalid literal for int() with base 10: 'hello'
Key Point: Runtime errors happen during program execution and will cause your program to terminate
unless handled properly.
3. Logic Errors - "Wrong Results"
These are the most challenging to identify. The code runs without crashing, but produces incorrect results
due to flawed logic.
Example: Incorrect Conditional Logic
score = 95
if score < 60:
print("You passed!") # Logic is backwards
else:
print("You failed!")
# Output: "You failed!" (Incorrect!)
Another Example: Missing elif
score = 85
if score >= 90:
grade = "A"
if score >= 80:
grade = "B"
if score >= 70:
grade = "C"
print("Grade:", grade) # Will print "C" even though 85 should be "B"
Key Point: Logic errors are difficult to detect because Python executes the code without any error
messages. Thorough testing is essential to identify these issues.
Part 3: Preventing Errors with Conditionals
The Defensive Programming Principle
Before performing any risky operation, verify that it is safe to proceed.
This is similar to checking the weather before planning an outdoor event, or looking both ways before
crossing the street.
Strategy: Validate Before Operating
The basic approach:
1. Accept user input or receive data
2. Check if the data is valid
3. If valid, proceed with the operation
4. If invalid, provide a helpful error message
Example 1: Safe Division
Without Validation (Dangerous):
a = 10
b = 0
answer = a / b # Program crashes with ZeroDivisionError
With Validation (Safe):
a = 10
b = 0
if b == 0:
print("Error: Cannot divide by zero")
else:
answer = a / b
print("Answer:", answer)
What Changed:
1. We check if b is zero BEFORE attempting division
2. If it is zero, we display an error message instead of crashing
3. If it is safe, we perform the division
Example 2: Age Validator
Without Validation:
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
Problem: This doesn't handle negative numbers or unreasonably large values like 200.
With Validation:
age = int(input("Enter your age: "))
if age < 0:
print("Error: Age cannot be negative")
elif age > 120:
print("Error: Age seems invalid")
elif age >= 18:
print("You are an adult")
else:
print("You are a minor")
Key Point: Always consider edge cases—values at the boundaries of acceptable ranges or beyond them.
Example 3: Score Validator
Without Validation:
score = int(input("Enter your score: "))
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Problem: What if the score is negative or greater than 100?
With Validation:
score = int(input("Enter your score: "))
if score < 0 or score > 100:
print("Error: Score must be between 0 and 100")
else:
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Part 4: Catching Errors with Try-Except
The Exception Handling Mechanism
Sometimes we cannot easily check beforehand whether an operation will succeed. In these cases, Python
provides the try-except mechanism to catch and handle errors gracefully.
Concept:
• Try to execute code that might fail
• If an exception occurs, catch it with except
• Execute alternative code instead of crashing
Basic Syntax
try:
# Code that might raise an exception
risky_operation()
except ExceptionType:
# Code to execute if exception occurs
print("An error occurred")
Example 1: Converting User Input to Integer
The Problem:
user_input = input("Enter a number: ")
number = int(user_input) # What if user enters "hello"?
print("Your number:", number)
If the user enters non-numeric text, this raises: ValueError: invalid literal for int()
The Solution:
user_input = input("Enter a number: ")
try:
number = int(user_input)
print("Your number:", number)
except ValueError:
print("Error: That is not a valid number")
What Happens:
1. The program tries to convert the input to an integer
2. If successful: The number is printed
3. If ValueError occurs: The error is caught and a user-friendly message is displayed
Example 2: Safe Calculator
Combining try-except with conditionals:
print("Simple Calculator")
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if num2 == 0:
print("Error: Cannot divide by zero")
else:
result = num1 / num2
print(f"Result: {result}")
except ValueError:
print("Error: Please enter valid numbers")
This handles TWO types of potential errors:
1. ValueError (via try-except): User enters non-numeric input
2. ZeroDivisionError (via if-else): Denominator is zero
Example 3: Multiple Exception Types
You can catch different exception types separately:
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
try:
x = int(num1)
y = int(num2)
result = x / y
print("Result:", result)
except ValueError:
print("Error: Please enter valid integers")
except ZeroDivisionError:
print("Error: Cannot divide by zero")
Example 4: Using else with try-except
The else clause executes only if no exception occurred:
number_input = input("Enter a number: ")
try:
number = int(number_input)
except ValueError:
print("Error: Invalid number")
else:
# This runs only if conversion succeeded
squared = number ** 2
print(f"The square of {number} is {squared}")
Part 5: When to Use Which Approach
Decision Guide
Understanding when to use conditionals versus try-except is crucial for writing clean, efficient code.
Use IF-ELSE When You Can Check Beforehand
Appropriate for:
• Checking if a number is zero before division
• Validating that values are within acceptable ranges
• Checking if a score is between 0-100
• Verifying that quantities are positive
Example:
score = 85
if score < 0 or score > 100:
print("Error: Invalid score")
else:
print("Valid score:", score)
Why? These are logical conditions that can be evaluated before performing the operation.
Use TRY-EXCEPT When You Cannot Easily Check Beforehand
Appropriate for:
• Converting strings to numbers (difficult to validate all possible string formats)
• File operations (file might not exist or might be locked)
• Network operations (connection might fail)
• Any operation that might fail in unpredictable ways
Example:
try:
age = int(input("Enter age: "))
print("Age:", age)
except ValueError:
print("Error: That is not a valid number")
Why? It's very difficult to check if a string can be converted to an integer without actually attempting the
conversion.
Combining Both Approaches (Recommended)
Most robust programs use both techniques:
try:
# Try to get and convert input
score = int(input("Enter score: "))
# Validate the converted value
if score < 0 or score > 100:
print("Error: Score must be between 0 and 100")
else:
print("Valid score:", score)
except ValueError:
print("Error: Please enter a valid number")
This protects against:
1. Non-numeric input (caught by try-except)
2. Out-of-range values (caught by if-else)
Comparison Table
Scenario Best Approach Reason
Checking if divisor is zero if-else Easy to check beforehand
Converting string to integer try-except Hard to validate all string formats
Validating age range (0-120) if-else Simple logical condition
Opening a file try-except File may not exist
Checking score is 0-100 if-else Clear boundary conditions
Multiple operations that might fail try-except Catches unexpected errors
Part 6: Common Beginner Mistakes
Mistake 1: Forgetting Input Type Conversion
INCORRECT
age = input("Enter age: ") # This returns a STRING
if age >= 18: # Comparing string to integer (unreliable)
print("Adult")
CORRECT
age = int(input("Enter age: ")) # Convert to integer first
if age >= 18:
print("Adult")
Important: The input() function always returns a string, regardless of what the user types.
Mistake 2: Using Generic Exception Handlers
LESS SPECIFIC (not recommended)
try:
number = int(input("Enter number: "))
except:
print("Error occurred")
MORE SPECIFIC (recommended)
try:
number = int(input("Enter number: "))
except ValueError:
print("Error: That is not a valid number")
Why specificity matters: Specific exception types provide clearer information about what went wrong
and allow for targeted error handling.
Mistake 3: Not Validating After Type Conversion
INCOMPLETE
try:
age = int(input("Enter age: "))
print("Age:", age)
except ValueError:
print("Error: Invalid input")
# What if user enters -5 or 200?
COMPLETE
try:
age = int(input("Enter age: "))
if age < 0 or age > 120:
print("Error: Age must be between 0 and 120")
else:
print("Age:", age)
except ValueError:
print("Error: Invalid input")
Mistake 4: Incorrect Order of Conditions
INCORRECT (all scores get multiple grades printed)
score = 95
if score >= 90:
print("Grade: A")
if score >= 80:
print("Grade: B")
if score >= 70:
print("Grade: C")
# Output prints all three grades!
CORRECT (only one grade printed)
score = 95
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
Part 7: Step-by-Step Problem Solving
Structured Approach to Writing Error-Safe Code
Follow this process when developing programs that require robust error handling:
Step 1: Write the basic functionality
price = input("Enter price: ")
quantity = input("Enter quantity: ")
total = price * quantity
print("Total:", total)
Step 2: Add try-except for type conversion
try:
price = float(input("Enter price: "))
quantity = int(input("Enter quantity: "))
total = price * quantity
print("Total:", total)
except ValueError:
print("Error: Please enter valid numbers")
Step 3: Add validation checks
try:
price = float(input("Enter price: "))
quantity = int(input("Enter quantity: "))
if price < 0:
print("Error: Price cannot be negative")
elif quantity < 1:
print("Error: Quantity must be at least 1")
else:
total = price * quantity
print(f"Total: ${total:.2f}")
except ValueError:
print("Error: Please enter valid numbers")
Step 4: Test thoroughly
Test with various inputs:
• Valid inputs (normal case)
• Text instead of numbers
• Negative values
• Zero values
• Very large numbers
• Boundary values
Part 8: Best Practices Checklist
Before Submitting Your Code
Verify that your program includes:
• ☐ Try-except blocks around input conversions
• ☐ Validation for negative numbers (where applicable)
• ☐ Check for division by zero
• ☐ Range validation (e.g., 0-100 for scores, 0-120 for age)
• ☐ Clear, specific error messages
• ☐ Testing with invalid inputs
• ☐ Proper use of elif instead of multiple if statements
• ☐ Specific exception types rather than generic except
Part 9: Quick Reference
Common Exception Types
Exception When It Occurs Example
ValueError Invalid value for the type int("hello")
ZeroDivisionError Division by zero 10 / 0
TypeError Operation on incompatible types "text" + 5
NameError Variable not defined Using undefined variable
SyntaxError Invalid Python syntax Missing colon, quotes
Error Handling Template
try:
# Step 1: Get input and convert to appropriate type
value = int(input("Enter value: "))
# Step 2: Validate using conditionals
if value < MINIMUM:
print("Error: Value too small")
elif value > MAXIMUM:
print("Error: Value too large")
else:
# Step 3: Perform calculations
result = process(value)
print("Result:", result)
except ValueError:
# Step 4: Handle conversion errors
print("Error: Please enter a valid number")
Part 10: Practice Exercises
Exercise 1: Temperature Validator
Write a program that:
1. Asks for temperature in Celsius
2. Validates that input is numeric
3. Checks that temperature is between -50 and 50
4. Displays "Valid temperature" if all checks pass
Exercise 2: Positive Number Doubler
Write a program that:
1. Asks for a number
2. Validates that input is numeric
3. Checks that number is positive
4. Doubles the number and displays the result
Exercise 3: Safe Division Calculator
Write a program that:
1. Asks for two numbers
2. Validates that both inputs are numeric
3. Checks that the second number is not zero
4. Performs division and displays the result with 2 decimal places