Skip to content
PythonModules, Files, and Errorsbeginner25 min read

Exceptions and Tracebacks

Understand runtime exceptions, read tracebacks, handle expected errors, and debug Python programs systematically.

In this lesson, you will learn

  • ✓Distinguish syntax errors from exceptions raised during program execution.
  • ✓Explain what an exception is and identify common built-in exception types.
  • ✓Read a traceback to locate the statement that failed and understand the error message.
  • ✓Use try, except, else, and finally to handle errors appropriately.
  • ✓Predict program output when an exception is raised and handled.
  • ✓Write and test a small program that handles invalid input without hiding unrelated programming errors.

1. What are exceptions?

An exception is an object that represents an error or an unusual condition detected while a program is running. When an operation cannot proceed normally, Python may raise an exception. If the program does not handle it, the exception can terminate the current program execution.

For example, int('abc') raises ValueError because 'abc' is not a valid integer representation. The expression 10 / 0 raises ZeroDivisionError because division by zero is not allowed for ordinary numeric division.

An exception is different from a syntax error. A SyntaxError occurs when Python cannot parse code correctly. Many other exceptions occur after Python has successfully parsed the program and begun executing it.

An exception raised during execution

An exception raised during execution
python
number = int('abc')
print(number)
print('Program finished')
Output
ValueError: invalid literal for int() with base 10: 'abc'

Python starts executing the first statement and calls int('abc'). Because 'abc' cannot be converted to an integer, Python raises ValueError. The assignment does not complete, so the following print statements are not executed during this run. The displayed error message is representative of a typical Python version; the full traceback also includes file and line information.

Note

A handled exception does not mean the original operation succeeded. It means the program recognized the error and followed the handling code instead of allowing that exception to remain unhandled.

2. Common built-in exceptions

Python provides many built-in exception types. Recognizing common ones helps you understand error messages and choose an appropriate except clause.

ValueError means an operation received a value of the right general type but could not use that value as requested. TypeError usually means an operation received an inappropriate type. IndexError occurs when a sequence index is outside its valid range, and KeyError occurs when a dictionary key is missing.

ZeroDivisionError is raised by ordinary numeric division by zero. FileNotFoundError can occur when an attempt to open a file cannot find the specified file. These examples are common, but the exact exception depends on the operation and circumstances.

Identify the exception

Identify the exception
python
values = [10, 20]
 
try:
print(values[5])
except IndexError:
print('Index is outside the list.')
Output
Index is outside the list.

The list has valid indexes 0 and 1. Index 5 does not identify an existing list element, so Python raises IndexError. The matching except block handles that exception and prints the message.

Note

Choose the exception type that matches the failure you expect. Catching the wrong exception will not handle the error.

3. How to read a traceback

A traceback is Python's report of the call sequence leading to an unhandled exception. It commonly includes the file name, line number, function names when applicable, the statement involved, and the exception type and message.

The last line usually gives the exception type and a short explanation. Read that line first to identify the kind of failure. Then inspect the preceding traceback entries to find where the error occurred and how execution reached that point.

A traceback can contain multiple frames when functions call other functions. The final frame generally identifies the statement where the exception was raised. Earlier frames show the chain of calls that led there. A traceback is a diagnostic clue, not a replacement for understanding the code.

Use a traceback to locate a division error

Use a traceback to locate a division error
python
def calculate_average(total, count):
return total / count
 
result = calculate_average(20, 0)
print(result)
Output
ZeroDivisionError: division by zero

The function is defined successfully. The call calculate_average(20, 0) passes 20 as total and 0 as count. The division total / count raises ZeroDivisionError. An actual unhandled traceback also identifies the file, the relevant line numbers, and the call path. Those line numbers depend on where the code is saved and executed. The correct fix depends on the intended behavior. For an average, a zero count may need validation before the division.

Note

The error message and the statement that raised the exception are often the best starting points. Do not assume that the final line alone explains every cause; inspect the relevant code and preceding calls.

4. Using try and except

Put code that may raise an expected exception inside a try block. Follow it with one or more except blocks that handle specific exception types. When an exception occurs in the try block, Python skips the remaining statements in that block and looks for a matching handler.

If no matching handler exists, the exception continues outward to a surrounding try block or remains unhandled. Statements after a handled try/except structure can then run normally, provided the handler itself does not raise another unhandled exception.

Avoid using a broad except clause simply to make errors disappear. Catching Exception without a good reason can hide unrelated programming mistakes. Catch the specific exception you know how to handle.

Catch only the expected error

Catch only the expected error
python
try:
print(10 / 0)
except ZeroDivisionError:
print('Cannot divide by zero')
 
print('Program continues')
Output
Cannot divide by zero Program continues

The division raises ZeroDivisionError. The matching handler prints the first message. Execution continues after the try/except statement, so the second message is printed.

Note

Python selects a matching handler based on the exception raised, not on which handler seems most relevant to the programmer.

5. The else and finally clauses

An optional else clause runs when the try block finishes without raising an exception handled by the associated except clauses. Put statements that should happen only after the try block succeeds in else when doing so makes the logic clearer.

An optional finally clause runs when control leaves the try statement, whether or not an exception occurred. It is commonly used for cleanup that must be attempted on both success and failure.

The clauses have different jobs: try contains the operation, except handles selected errors, else handles the successful path, and finally performs cleanup. A finally block can still affect how an exception propagates if it raises an exception or changes control flow, so avoid returning from finally or using it to suppress errors.

Use else after a successful conversion

Use else after a successful conversion
python
text = '42'
 
try:
number = int(text)
except ValueError:
print('Invalid integer.')
else:
print('Converted:', number)
Output
Converted: 42

The conversion succeeds, so no ValueError handler runs. Because the try block finishes without an exception, the else block executes. The print statement displays the label and converted integer separated by a space.

Note

For files, prefer using with open(...) as file because the context manager closes the file when the block is exited, including when an exception occurs.

6. Prevent errors and raise exceptions deliberately

Exception handling is not the only way to make a program reliable. When a condition can be checked before an operation, validating it first can make the program's behavior easier to understand.

For example, check whether a divisor is zero before dividing if zero is not allowed by the application's rules. When an operation should reject an invalid argument, a function can raise an exception deliberately with raise. The caller can then decide whether to handle it.

Do not add checks blindly for every possible situation. Validate conditions that matter to the function's requirements, and use clear error messages or appropriate exception types to explain invalid operations.

Raise an exception for invalid input

Raise an exception for invalid input
python
def divide(a, b):
if b == 0:
raise ValueError('The divisor must not be zero.')
return a / b
 
try:
print(divide(10, 0))
except ValueError as error:
print(error)
Output
The divisor must not be zero.

The divide function checks its argument before dividing. When b is zero, raise creates and raises a ValueError with the supplied message. The caller catches ValueError and stores the exception object in error. Printing the exception object displays its message. ValueError is a deliberate choice here to illustrate validation. Other APIs may choose a different exception type according to their contract.

Caution

Do not catch an exception and silently ignore it unless ignoring that specific failure is an intentional, safe part of the program's design. Silent failures make debugging and testing much harder.

7. A practical debugging workflow

When a Python program raises an exception, work through the failure systematically rather than changing unrelated lines at random.

First, read the exception type and message. Next, locate the line identified by the traceback and inspect the values used in that operation. Follow earlier traceback frames if the line is inside a function called by other code. Reproduce the problem with a small input, determine whether the input or implementation violates the requirement, and make the smallest appropriate correction.

After the correction, rerun the failing case and test a normal case and relevant boundary cases. If the program handles invalid input, verify that it handles only the intended errors and that unrelated programming errors are still visible.

Trace an invalid conversion

Trace an invalid conversion
python
def read_age(text):
age = int(text)
return age
 
try:
print(read_age('twenty'))
except ValueError:
print('Age must be entered as a whole number.')
Output
Age must be entered as a whole number.

The call passes the string 'twenty' to read_age. Inside the function, int(text) raises ValueError. The exception travels back through the function call until the surrounding handler catches it. The print inside the try block does not run because read_age does not return successfully. The handler provides a useful message for this expected invalid input.

Note

A traceback tells you where execution failed; debugging means using that information and the program's requirements to identify and correct the underlying cause.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Confusing a syntax error with an exception raised during execution.

Why it happens: Syntax errors prevent Python from parsing the program, while exceptions occur during execution after parsing succeeds.

Incorrect Approach
script.py
python
Confusing a syntax error with an exception raised during execution.
Correct Solution
script.py
python
A SyntaxError means Python cannot parse the code as written. Exceptions such as ValueError and ZeroDivisionError can be raised while otherwise valid code executes.

Key takeaway: A SyntaxError means Python cannot parse the code as written. Exceptions such as ValueError and ZeroDivisionError can be raised while otherwise valid code executes.

#2 Reading only the first traceback line or ignoring the final error message.

Why it happens: The final traceback line names the exception and message, while preceding frames help identify the execution path and relevant source line.

Incorrect Approach
script.py
python
Reading only the first traceback line or ignoring the final error message.
Correct Solution
script.py
python
Read the final exception type and message first, then inspect the relevant file, line number, statement, and earlier function calls.

Key takeaway: Read the final exception type and message first, then inspect the relevant file, line number, statement, and earlier function calls.

#3 Using except ValueError to catch every kind of error.

Why it happens: except ValueError handles that specific exception type, not unrelated errors such as TypeError, KeyError, or ZeroDivisionError.

Incorrect Approach
script.py
python
Using except ValueError to catch every kind of error.
Correct Solution
script.py
python
Catch the specific exception you expect. ValueError does not handle unrelated exceptions such as ZeroDivisionError or IndexError.

Key takeaway: Catch the specific exception you expect. ValueError does not handle unrelated exceptions such as ZeroDivisionError or IndexError.

#4 Assuming statements after a failing operation in the try block will still run.

Why it happens: When an operation raises an exception, execution jumps to a matching handler, so later statements in that try suite are skipped.

Incorrect Approach
script.py
python
Assuming statements after a failing operation in the try block will still run.
Correct Solution
script.py
python
When an exception is raised, Python skips the remaining statements in that try block and looks for a matching handler.

Key takeaway: When an exception is raised, Python skips the remaining statements in that try block and looks for a matching handler.

#5 Using except: pass to make an error disappear.

Why it happens: A bare pass handler hides failures and removes useful diagnostic information, making defects harder to detect and fix.

Incorrect Approach
script.py
python
Using except: pass to make an error disappear.
Correct Solution
script.py
python
Handle only errors the program can recover from. If an unexpected error indicates a bug, allow it to remain visible or handle it at a suitable boundary with meaningful reporting.

Key takeaway: Handle only errors the program can recover from. If an unexpected error indicates a bug, allow it to remain visible or handle it at a suitable boundary with meaningful reporting.

#6 Assuming finally runs only when an exception occurs.

Why it happens: finally runs whether the try suite succeeds or raises an exception, making it suitable for cleanup that must happen in either case.

Incorrect Approach
script.py
python
Assuming finally runs only when an exception occurs.
Correct Solution
script.py
python
The finally block runs when control leaves the try statement on both successful and exceptional paths, subject to normal Python control-flow behavior.

Key takeaway: The finally block runs when control leaves the try statement on both successful and exceptional paths, subject to normal Python control-flow behavior.

#7 Assuming a handled exception means the failed operation produced a valid result.

Why it happens: Catching an exception controls program flow but does not make the failed operation succeed; code must handle the failure and establish a valid result.

Incorrect Approach
script.py
python
Assuming a handled exception means the failed operation produced a valid result.
Correct Solution
script.py
python
The original operation may have failed. The handler must decide what the program should do next, such as display a message, use a safe fallback, or ask for another value.

Key takeaway: The original operation may have failed. The handler must decide what the program should do next, such as display a message, use a safe fallback, or ask for another value.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is an exception in Python?
Answer:
An exception is an object representing an error or unusual condition detected during execution. When an operation raises an exception, Python searches for a matching handler. If none handles it, the exception can terminate the current program execution and produce a traceback.
Q2:What is the difference between a syntax error and an exception such as ValueError?
Answer:
A syntax error means Python cannot parse the code correctly. ValueError is commonly raised during execution when an operation receives a value of an appropriate general type but cannot use that value as requested, such as converting 'abc' to an integer.
Q3:How do you read a Python traceback?
Answer:
Start with the final exception type and message. Then inspect the relevant file and line number and read the traceback frames to understand which calls led to the failing statement. Use the code and the values involved to determine the cause.
Q4:What is the purpose of try and except?
Answer:
The try block contains code that may raise an expected exception. An except block handles a matching exception. When an exception is raised, Python skips the remaining statements in the try block and looks for an appropriate handler.
Q5:What is the difference between else and finally in exception handling?
Answer:
The else block runs when the try block completes without an exception handled by its except clauses. The finally block runs when control leaves the try statement, on both successful and exceptional paths, and is commonly used for cleanup.
Q6:Why should you avoid catching every exception indiscriminately?
Answer:
A broad handler can hide unexpected programming errors and make failures difficult to diagnose. Prefer catching specific exceptions that the program knows how to handle, and provide a meaningful recovery action.
Q7:What does raising an exception do?
Answer:
The raise statement signals an error or invalid condition by raising an exception object. The exception propagates until a matching handler catches it or it remains unhandled. Functions can use this to enforce their requirements and let callers decide how to respond.

Key takeaways

  • An exception represents an error or unusual condition detected during program execution.
  • Common exceptions include ValueError, TypeError, IndexError, KeyError, ZeroDivisionError, and FileNotFoundError.
  • A traceback helps identify the exception, the failing statement, and the call sequence that led to it.
  • Use try and except to handle expected errors with specific, meaningful recovery behavior.
  • The else clause runs after a successful try block; finally is commonly used for cleanup.
  • Use raise when a function must report an invalid condition to its caller.
  • Fix the underlying cause where appropriate, and test normal, boundary, and invalid inputs after making a change.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: