Python Error Types & Exception Handling — Study Guide
Introduction to Errors
Errors are issues or defects that prevent a program from executing correctly. Understanding different
types of errors helps in writing robust and bug-free code.
Types of Errors in Python
1. Syntax Error
Occurs due to formatting mistakes.
Also called Parsing Errors.
Example:
print("Youth Af"
2. Logical Error
Occurs due to flawed logic.
Code runs but gives incorrect or unexpected output.
Example:
# Intended to perform addition print(6 - 9)
3. Runtime Error
Errors that occur during program execution.
Also called Exceptions.
Common causes:
o Dividing by zero
o Opening a non-existent file
Example:
print(5 / 0)
Exception Handling
A mechanism to handle runtime errors.
Prevents the program from crashing.
Allows the programmer to manage unexpected situations using try-except blocks.
Quick Tips for Error Management
✅ Test your code for edge cases.
✅ Use try-except to catch and handle exceptions.
✅ Debug logical errors by tracing the flow and expected outcomes.
Core Exception Handling Keywords with Code Examples
try
Tests a block of code for errors.
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except
Handles the error if one occurs in the try block. (See above)
else
Executes if no error occurs in the try block.
try:
x = 10 / 2
except ZeroDivisionError:
print("Error")
else:
print("Division successful:", x)
finally
Executes code regardless of the result of try and except.
try:
x = 10 / 0
except ZeroDivisionError:
print("Error")
finally:
print("This always runs")
raise
Used to raise a custom exception.
def check_age(age):
if age < 18:
raise ValueError("Must be at least 18")
check_age(15)
assert
Tests an expression; raises an exception if the result is false.
x=5
assert x > 10, "x must be greater than 10"
⚠️Common Python Errors / Exceptions with Code Examples
ZeroDivisionError
Raised when attempting to divide a number by zero.
x = 10 / 0
ValueError
Raised when an invalid argument or input is provided.
int("abc")
IOError (OSError)
Raised when an I/O operation (e.g., file read/write) fails.
open("[Link]")
TypeError
Raised when an operation is applied to an inappropriate data type.
len(42)
NameError
Raised when a variable or function name is not found in the current scope.
print(undeclared_variable)
IndexError
Raised when an index is out of range for a list, tuple, etc.
lst = [1, 2, 3] print(lst[5])
KeyError
Raised when a key is not found in a dictionary.
my_dict = {"a": 1} print(my_dict["b"])
✅ Quick Notes
Use try-except blocks to handle exceptions gracefully.
else runs only if no exception occurs.
finally is useful for cleanup actions like closing files or releasing resources.
raise and assert help enforce custom logic and validation.