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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is an exception in Python?
Q2:What is the difference between a syntax error and an exception such as ValueError?
Q3:How do you read a Python traceback?
Q4:What is the purpose of try and except?
Q5:What is the difference between else and finally in exception handling?
Q6:Why should you avoid catching every exception indiscriminately?
Q7:What does raising an exception do?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: