When programming in Python, you will encounter various “exceptions (errors).” While error messages might look difficult at first glance, they are actually important hints that tell you exactly “what is wrong.” Knowing the causes of each type of exception will dramatically improve your debugging speed.
This article explains representative exceptions frequently seen in Python development and their causes.
List of Representative Exceptions
1. AttributeError
Occurs when you try to use an attribute (variable) or method that an object does not possess. This often happens due to typos or misunderstanding the variable’s type.
# Numeric type (int) does not have an append method
number = 100
# Error: 'int' object has no attribute 'append'
# number.append(5)
2. IndexError
Occurs when you specify a non-existent index (out of range position) for a sequence type like a list or tuple.
# List with only 3 elements (indices are 0, 1, 2)
menu_items = ["Coffee", "Tea", "Water"]
# Trying to access non-existent index 5
# Error: list index out of range
# item = menu_items[5]
3. KeyError
Occurs when you try to access a dictionary (dict) using a key that does not exist.
# User info dictionary
user_data = {"id": 101, "name": "Tanaka"}
# Trying to get non-existent key "email"
# Error: 'email'
# email = user_data["email"]
Common solutions include using the .get() method or checking existence beforehand with the in operator.
4. TypeError
Occurs when you pass an object of an inappropriate “type” to an operation or function. For example, trying to add a number and a string directly.
price = 1000
tax_str = "0.1" # String
# Cannot add number and string
# Error: unsupported operand type(s) for +: 'int' and 'str'
# total = price + tax_str
5. ValueError
Occurs when the type (class) itself is correct, but its “value” is inappropriate. A typical example is passing a string that cannot be interpreted as a number when converting a string to a number.
# "123" can be converted to int, but "hello" cannot
input_text = "hello"
# Error: invalid literal for int() with base 10: 'hello'
# number = int(input_text)
6. ZeroDivisionError
Occurs when trying to divide a number by 0. This is a calculation that is mathematically undefined.
count = 0
total = 500
# Division by zero
# Error: division by zero
# average = total / count
Exception Hierarchy (Inheritance Relationship)
All Python exceptions are defined as classes and have a hierarchical structure.
- BaseException The base (root) class for all exceptions. It includes not only normal program errors but also system exits (
SystemExit) and keyboard interrupts (KeyboardInterrupt). - Exception The base class for exceptions that occur in normal programs. It inherits from
BaseExceptionbut does not include system exits, etc.
Which one should you catch?
If you want to catch a wide range of errors with a try-except statement, you should specify Exception, not BaseException.
try:
# Some processing
pass
except Exception as e:
# Catch only normal errors (Recommended)
print(f"Error: {e}")
If you write except BaseException: or just except:, you might capture signals like force quit (e.g., pressing Ctrl+C), potentially making it impossible to stop the program.
Summary
When an error occurs, first check the “Exception Name”.
- AttributeError: Missing attribute or method.
- IndexError: List index out of range.
- KeyError: Missing dictionary key.
- TypeError: Type mismatch.
- ValueError: Invalid value format.
- ZeroDivisionError: Dividing by zero.
If you understand these meanings, you can guess the location of the fix the moment you see the error message.
