Fundamentals 7 min read

Python Error Handling, try...except...finally, and Debugging Techniques

This article explains Python error handling using try...except...finally, demonstrates how to interpret tracebacks, and introduces debugging techniques such as print statements, assertions, and the pdb module, providing code examples and practical guidance for developers.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Error Handling, try...except...finally, and Debugging Techniques

In any program execution, various errors are inevitable; they may stem from logical oversights or unexpected user actions that lead the program into unhandled scenarios.

When Python outputs an error message to the console, the first step is to locate the point where the error occurred.

For example, the following code:

<code>deftest(name):
    return int(name)

test("cbekd")</code>

produces the traceback:

<code>Traceback (most recent call last):
  File "test.py", line 3, in <module>
    test()
  File "test.py", line 2, in test
    return int("cbekd")
ValueError: invalid literal for int() with base 10: 'cbekd'</code>

The traceback shows the call sequence from program start to the point of failure, indicating that the error originates on line 2 where a non‑numeric string is converted to an integer.

Beginners often resolve such issues by searching the exact error message online, which usually leads to explanations and solutions.

However, when dealing with more specialized or complex modules, direct searches become less effective, and developers must rely on interpreting error messages and consulting official documentation.

try...except...

Python provides the try , except , and finally constructs for error handling. Code placed inside try is executed; if an exception occurs, execution jumps to the matching except block, skipping the remaining try code. The finally block runs regardless of whether an exception was raised.

Example:

<code>try:
    print("try...before...")
    int("cbekd")
    print("try...after...")
except ValueError as e:
    print("except...", "detail:", e)
finally:
    print("finally...")</code>

Result:

<code>try...before...
except... detail: invalid literal for int() with base 10: 'cbekd'
finally...</code>

Multiple except blocks can handle different exception types, and because all Python exceptions inherit from BaseException , using except BaseException catches any exception.

Debugging Techniques

Sometimes the location shown by a traceback is not the root cause; a variable may hold an incorrect value earlier in the execution. In such cases, inserting print() statements or assert checks helps trace variable values, a method often called "breakpoint debugging".

Python’s built‑in pdb module offers interactive debugging, allowing you to set breakpoints, step through code, and inspect state. After inserting pdb.set_trace() , the program pauses and waits for debugger commands.

Common pdb commands include n (next), c (continue), p (print), and pp (pretty‑print).

Example with pdb :

<code>import pdb

def test(name):
    pdb.set_trace()
    return int(name)

test("cbekd")</code>

Running the script yields a debugging session such as:

<code>> test.py(5)test()
-> return int(name)
(Pdb) pp name
'cbekd'
(Pdb) n
ValueError: invalid literal for int() with base 10: 'cbekd'
>> test.py(5)test()
-> return int(name)
(Pdb)</code>

These examples illustrate how to interpret tracebacks, use structured error handling, and apply debugging tools to efficiently locate and fix bugs in Python code.

debuggingerror handlingtry-exceptpdb
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.