Python Error Types
In Python, errors can be broadly categorized into three main
types: syntax errors, runtime errors, and logical errors.
Syntax Errors
Syntax errors occur when the Python interpreter cannot parse the
code due to incorrect syntax. These errors are detected before the
program is executed. For example:
# Incorrect syntax: missing parentheses in print function
print "hello"
This will raise a SyntaxError:
SyntaxError: Missing parentheses in call to 'print'. Did you mean
print("hello")?
To fix this, you need to correct the syntax:
print("hello")
Runtime Errors
Runtime errors, also known as exceptions, occur during the
execution of the program. These errors can be caused by various
issues such as division by zero, accessing an invalid index, or
calling a function that does not exist. Some common runtime
errors include:
• NameError: Raised when a variable or function name is not
found.
# NameError example
print(age) # Raises NameError: name 'age' is not defined
• TypeError: Raised when an operation or function is applied
to an object of inappropriate type.
# TypeError example
result = '2' + 2 # Raises TypeError: can only concatenate str (not
"int") to str
• IndexError: Raised when trying to access an index that is
out of range.
# IndexError example
L1 = [1, 2, 3]
print(L1[3]) # Raises IndexError: list index out of range
• KeyError: Raised when a dictionary key is not found.
# KeyError example
D1 = {'1': "aa", '2': "bb", '3': "cc"}
print(D1['4']) # Raises KeyError: '4'
• ZeroDivisionError: Raised when the second operand of a
division or modulo operation is zero.
# ZeroDivisionError example
x = 100 / 0 # Raises ZeroDivisionError: division by zero
Logical Errors
Logical errors occur when the code runs without any syntax or
runtime errors but produces incorrect results due to flawed logic.
These errors are often the hardest to detect because the code
executes without any error messages. For example:
# Logical error example
def calculate_factorial(n):
result = 1
for i in range(1, n):
result *= i
return result
print(calculate_factorial(5)) # Incorrect output: 24
The correct code should include the number n in the range:
def calculate_factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(calculate_factorial(5)) # Correct output: 120
Handling Errors
To handle errors gracefully, Python provides the try-
except block. This allows you to catch and handle exceptions that
might otherwise cause your program to crash. For example:
try:
x = int(input("Enter a number: "))
y = 10 / x
print("The result is:", y)
except ValueError:
print("You must enter a valid integer.")
except ZeroDivisionError:
print("You cannot divide by zero.")
This code will handle
both ValueError and ZeroDivisionError exceptions, providing a
better user experience and preventing the program from crashing.
Understanding and handling these error types effectively can
significantly improve the reliability and robustness of your
Python applications.