Python Errors and Exceptions: Types, Handling, and Debugging
Python uses exceptions to report problems while your program runs, such as bad input, missing data, or illegal operations. Some errors stop the program immediately, while others can be caught and handled so the program can recover or show a useful message. This article explains what errors and exceptions are, how Python raises them, and how to use them correctly.
Difficulty: Beginner
Helpful to know first: basic Python syntax, variables, and how function calls work.
How Python Uses Errors to Stop or Redirect a Program
In Python, an error is a problem that prevents your code from continuing normally. Many Python problems are reported as exceptions, which are objects that describe what went wrong and where it happened. If an exception is not handled, Python prints a traceback and stops the program.
Here is the smallest useful example:
print(10 / 0) # ZeroDivisionErrorThis code tries to divide by zero, which is not allowed. Python raises a ZeroDivisionError and stops before it can print a result.
Not all errors happen at the same time. Some are caught before the program starts running, such as invalid syntax. Others happen while the program is running, such as dividing by zero or looking up a missing dictionary key. The rest of this article shows how to read these errors, handle them, and avoid common mistakes.
How a Traceback Tells You What Broke
When Python cannot continue, it prints a traceback. A traceback shows the call path from your code to the line where the exception happened. The last line usually matters most because it names the exception type and the message.
For example:
def calculate_share(total, people):
return total / people
print(calculate_share(25, 0))
# Traceback (most recent call last):
# ...
# ZeroDivisionError: division by zeroThe traceback tells you that the problem happened inside calculate_share(), not in the print() call itself. The message division by zero explains the immediate cause.
Read tracebacks from the bottom up: the last line gives the exception type and message, and the lines above it show where the call came from.
Common Python Exceptions You Will See Early
Some exceptions appear often in beginner code. Learning these names helps you recognize what Python is telling you.
ValueError for a right type with a bad value
A ValueError means the data type is acceptable, but the value itself is not.
int("12.5") # ValueError: invalid literal for int() with base 10: '12.5'The string is text, and text can be passed to int(), but "12.5" is not a valid integer literal. Use float() first if you want to parse decimals.
TypeError for using the wrong kind of object
A TypeError means the operation does not make sense for the object type.
print("age: " + 20) # TypeError: can only concatenate str (not "int") to strPython does not join text and integers automatically here. Convert the number first with str().
IndexError for an invalid list position
An IndexError means you tried to access a list element outside the valid range.
colors = ["red", "green"]
print(colors[2]) # IndexError: list index out of rangeList indexes start at 0, so the valid indexes here are 0 and 1.
KeyError for a missing dictionary key
A KeyError means a dictionary lookup used a key that is not present.
prices = {"apple": 1.50}
print(prices["banana"]) # KeyError: 'banana'Use dict.get() when the key may be missing.
How to Handle Exceptions with try and except
Use try and except when you want to catch an exception and do something else instead of crashing. The code inside try runs first. If an exception happens, Python skips the rest of the try block and runs the matching except block.
try:
number = int("not a number")
except ValueError:
print("Please enter a whole number.") # Output: Please enter a whole number.This code catches only ValueError. That is better than catching every exception, because it keeps unrelated bugs visible.
Using else for code that should run only if no exception happens
The else block runs only when the try block finishes without an exception.
try:
age = int("21")
except ValueError:
print("Invalid input")
else:
print("Age is", age) # Output: Age is 21Use else when you want to separate the normal path from the error path.
Using finally for cleanup that must always happen
The finally block runs whether or not an exception happened. It is often used for cleanup, such as closing a file or releasing a resource.
try:
print(10 / 2)
finally:
print("Done") # Output: 5.0 then DoneEven if something fails inside try, the finally code still runs.
How to Raise Your Own Exceptions
You can use raise to stop execution when a value is invalid. This is useful when your function depends on a rule that Python does not know about.
def withdraw(balance, amount):
if amount > balance:
raise ValueError("amount cannot exceed balance")
return balance - amount
print(withdraw(100, 30)) # Output: 70This function checks a business rule before doing the subtraction. If the rule is broken, it raises a clear exception with a useful message.
You can also re-raise an exception after adding context, but do that only when it helps debugging. In many beginner cases, a clear message is enough.
What Exception Hierarchy Means in Practice
Python exceptions are organized in a hierarchy. Exception is a common base class for many errors you usually want to catch. Specific exceptions, such as ValueError and IndexError, inherit from it.
This matters because you can catch a broad group or one specific problem. For example, this catches any normal runtime exception:
try:
print(1 / 0)
except Exception as error:
print(type(error).__name__) # Output: ZeroDivisionErrorCatching Exception is sometimes useful in top-level application code, but it is usually too broad inside ordinary functions. Catch the specific exception you expect, so real bugs are not hidden.
Why Some Errors Are Syntax Errors and Others Are Exceptions
A SyntaxError happens before Python can run the program. The code is not valid Python, so the interpreter cannot even build the program structure.
print("Hello"
# SyntaxError: '(' was never closedThis is different from exceptions such as ValueError or IndexError, which happen after Python has started running valid code. A syntax problem must be fixed in the source code itself before anything can run.
How Common Errors Behave in Real Code
The same exception type can appear in many different situations. These examples show why the message matters as much as the exception name.
Missing input causes ValueError
If you try to convert empty text into a number, Python raises an exception because the value does not match the type you asked for.
text = ""
try:
print(int(text))
except ValueError as error:
print(error) # Output: invalid literal for int() with base 10: ''The fix is to validate the input before converting it, or handle the exception and ask again.
Off-by-one loops cause IndexError
A loop that goes one step too far often causes an IndexError.
names = ["Ana", "Bo"]
for i in range(3):
print(names[i])
# Output:
# Ana
# Bo
# IndexError: list index out of rangeThe range should match the list length, or better, iterate directly over the list.
Wrong key names cause KeyError
Dictionary keys are exact. A small spelling difference creates a missing-key error.
profile = {"name": "Mina"}
try:
print(profile["Name"])
except KeyError as error:
print(error) # Output: 'Name'The fix is to use the exact key or choose dict.get() with a default value.
How Errors and Exceptions Help You Debug Faster
Exceptions are not just failures. They also give you clues. The exception type tells you the category of problem, and the message tells you the specific reason. The traceback tells you where the problem occurred and how your code got there.
When you see an error, ask three questions:
- What exception type is it?
- What line in my code caused it?
- What value or object made the operation fail?
For example, TypeError usually means you passed the wrong kind of object into an operation. ValueError usually means the object type was fine, but the value itself was invalid. That distinction helps you choose the right fix quickly.
Predict the Output
List aliasing and shared changes
a = [1, 2]
b = a
b.append(3)
print(a)What does this print?
Show answer
It prints [1, 2, 3]. Both names refer to the same list object, so changing b also changes a.
Range and off-by-one confusion
for i in range(1, 4):
print(i)What does this print?
Show answer
It prints 1, 2, and 3 on separate lines. The stop value in range() is excluded, so 4 is not printed.
Find the Bug
This function is meant to average a list of numbers, but it crashes for some inputs and gives a misleading result for others. Find the bug.
def average(values = []):
total = 0
for value in values:
total += value
return total / len(values)
print(average())What is wrong with this code, and how should it be fixed?
Show answer
The bug is that the function can divide by zero when values is empty. The default empty list also invites confusion, because a function that takes no input should usually not promise an average.
Fixed code:
def average(values = None):
if values is None:
raise ValueError("values cannot be empty")
if len(values) == 0:
raise ValueError("values cannot be empty")
total = 0
for value in values:
total += value
return total / len(values)The corrected version fails with a clear exception instead of dividing by zero.
When to Catch an Exception and When to Let It Fail
Use exception handling when a failure is expected and recoverable. Do not catch exceptions just to hide them. If a function cannot do its job because of a programming mistake, it is often better to let the exception fail loudly so you can fix the bug.
| Situation | Better choice | Why |
|---|---|---|
| User typed letters instead of a number | Catch ValueError | The input can be corrected and asked again. |
| Missing dictionary key that is optional | Use dict.get() or catch KeyError | The program can use a default value. |
| Bug in your own logic | Let the exception fail or raise a clearer one | Hiding the bug makes it harder to find. |
As a rule, catch the smallest exception that you can handle meaningfully. Catching too much can make real bugs harder to see.
Common Mistakes With Python Errors and Exceptions
Catching every exception and hiding real bugs
Some beginners use a broad except block and then print a generic message. That can make debugging much harder because unrelated failures disappear.
Problem: This code hides every error, including mistakes you did not expect.
try:
result = 10 / 0
except:
print("Something went wrong")Fix: Catch the specific exception you expect.
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero.")The fixed version still handles the problem, but it does not hide other exceptions.
Using the wrong exception type for invalid input
Not every bad value deserves the same exception. If the type is correct but the value is not, ValueError is often the right choice.
Problem: This code raises the wrong exception type for a value rule, which makes the failure less accurate.
def set_percent(value):
if value < 0 or value > 100:
raise TypeError("value must be between 0 and 100")
return valueFix: Use ValueError because the object type can be correct while the numeric value is invalid.
def set_percent(value):
if value < 0 or value > 100:
raise ValueError("value must be between 0 and 100")
return valueThe corrected version matches the problem more closely, which makes debugging and testing clearer.
Assuming a list index is always valid
Code that depends on a position in a list should check the length first or handle the possible IndexError.
Problem: This code assumes the list has at least one item, so it fails on an empty list.
items = []
print(items[0])Fix: Check whether the list is empty before indexing it.
items = []
if items:
print(items[0])
else:
print("No items available")The fixed version avoids the exception by checking the data before it uses the index.
Try It Yourself
Write a program that asks for a number, converts it to int, and prints its square. If the input is not a valid whole number, print a friendly error message instead of crashing.
- Store the input in a variable.
- Use try and except to catch ValueError.
- On success, print the square.
- On failure, print "Please enter a whole number."
Expected output:
If the user enters 7, the program should print 49.
Hint: Use input() to read text, then convert it with int().
Show solution
text = input("Enter a whole number: ")
try:
number = int(text)
except ValueError:
print("Please enter a whole number.")
else:
print(number * number)Summary
- Python uses exceptions to report runtime problems such as bad input, missing keys, and invalid indexes.
- The traceback shows where the problem happened and the last line usually names the exact exception.
- try, except, else, and finally let you control how your program reacts to failures.
- Catching specific exceptions is safer than catching everything.
- raise lets you create clear errors when your own function rules are broken.
- SyntaxError is different from a runtime exception because the code is not valid Python in the first place.
Next, learn about try/except blocks in more detail so you can handle failures without hiding real bugs.