Python Error Handling
Learn to handle errors gracefully with try/except, understand common error types, raise exceptions, and debug your code.
Types of Errors in Python
Errors (also called exceptions) occur when Python encounters something it cannot process. Understanding the different types helps you write more robust code.
SyntaxError
Code breaks Python's grammar rules, like missing a colon or bracket.
NameError
Using a variable or function that has not been defined.
TypeError
Wrong data type used, like adding a string and an integer.
ValueError
Right type but wrong value, like int("abc").
# Common errors demonstrated
# print("Hello" # SyntaxError: missing closing bracket
# print(undefined_var) # NameError: variable not defined
# "hello" + 5 # TypeError: can't add str and int
# int("abc") # ValueError: can't convert "abc" to int
# numbers = [1, 2, 3]
# numbers[10] # IndexError: index out of range
# data = {"a": 1}
# data["z"] # KeyError: key not found
try/except Blocks
The try/except block lets you catch errors and handle them gracefully instead of crashing. You can also use else (runs if no error) and finally (always runs).
# Basic try/except
try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"100 / {number} = {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}")
else:
print("Calculation successful!")
finally:
print("This always runs, error or not.")
Raising Exceptions and Debugging
You can raise your own exceptions when something is wrong in your program's logic. The raise keyword creates an error intentionally. Good debugging involves reading error messages carefully and using print statements to trace issues.
def set_age(age):
if not isinstance(age, int):
raise TypeError("Age must be an integer")
if age < 0 or age > 150:
raise ValueError(f"Age {age} is not valid (must be 0-150)")
return age
# Testing with try/except
try:
valid_age = set_age(25)
print(f"Age set to: {valid_age}")
invalid_age = set_age(-5)
except ValueError as e:
print(f"Caught error: {e}")
except TypeError as e:
print(f"Caught error: {e}")
Key Vocabulary
Exception
An error that occurs during program execution, like ValueError or TypeError.
try/except
A block that catches errors so the program can handle them instead of crashing.
raise
A keyword that intentionally triggers an exception when invalid conditions are detected.
Debugging
The process of finding and fixing errors (bugs) in your code.
Worked Examples
Safe number input with error handling
def get_number(prompt):
while True:
try:
value = float(input(prompt))
return value
except ValueError:
print("Invalid input. Please enter a number.")
# This will keep asking until a valid number is entered
num = get_number("Enter your score: ")
print(f"You entered: {num}")
Step 1: The function uses a while True loop with try/except.
Step 2: If the user enters non-numeric text, the ValueError is caught and they are asked again.
Safe file reading with error handling
def read_file_safely(filename):
try:
with open(filename, "r") as file:
content = file.read()
return content
except FileNotFoundError:
print(f"Error: '{filename}' not found.")
return None
except PermissionError:
print(f"Error: No permission to read '{filename}'.")
return None
# Test with a file that may or may not exist
content = read_file_safely("data.txt")
if content is not None:
print(f"File has {len(content)} characters")
Step 1: We handle FileNotFoundError and PermissionError separately.
Step 2: The function returns None on error so the caller can check.
Custom validation with raise
def create_student(name, score):
if not isinstance(name, str) or len(name) == 0:
raise ValueError("Name must be a non-empty string")
if not isinstance(score, (int, float)):
raise TypeError("Score must be a number")
if score < 0 or score > 100:
raise ValueError("Score must be between 0 and 100")
return {"name": name, "score": score}
# Test cases
try:
s1 = create_student("Alice", 92)
print(f"Created: {s1}")
s2 = create_student("", 85)
except ValueError as e:
print(f"Validation error: {e}")
Step 1: The function validates all inputs and raises specific errors.
Output: Created: {'name': 'Alice', 'score': 92} | Validation error: Name must be a non-empty string
Knowledge Check
Select the correct answer for each question. Click "Check Answer" to see if you are right.
Question 1
What error does int("hello") produce?
Question 2
Which block catches errors in Python?
Question 3
When does the finally block run?
Question 4
What keyword is used to intentionally trigger an error?
Question 5
What error occurs when you access index 5 of a list with only 3 items?
Key Concepts Summary
- ● Common errors: SyntaxError, NameError, TypeError, ValueError, IndexError, KeyError.
-
●
Use
try/exceptto catch errors and prevent crashes. -
●
elseruns when no error occurs;finallyalways runs. -
●
Use
raiseto create your own exceptions for input validation. - ● Always read error messages carefully - they tell you the type and line number of the error.