Fundamentals 6 min read

Python Exception Handling and Debugging Techniques

This article explains Python's exception handling with try‑except‑finally blocks, demonstrates common error‑handling patterns, and presents ten practical debugging techniques—including print statements, assertions, logging, breakpoints, traceback, unit testing, and profiling—each illustrated with clear code examples.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Exception Handling and Debugging Techniques

Exception handling is a mechanism that captures and processes errors during program execution. In Python, exceptions such as division‑by‑zero, index errors, or type errors can be caught using try and except blocks to prevent crashes and allow recovery.

A basic example shows how a ZeroDivisionError is raised in the try block and handled in the except block:

try:
    # code that may raise an exception
    result = 10 / 0
except ZeroDivisionError:
    # handle the specific exception
    print("除零错误发生")

Beyond catching specific exceptions, multiple exception types can be caught, or a bare except can catch all errors. A finally block can be added to execute code regardless of whether an exception occurs.

The article then introduces ten practical debugging scenarios and tools:

1. Print debugging information – use print statements to display variable values and program state.

def my_function():
    print("进入函数")
    # print key variable
    print("变量 x =", x)
    # perform operations
    ...

2. Assertions – verify assumptions with assert, raising AssertionError when a condition fails.

def my_function(x):
    assert x > 0, "x 必须大于 0"
    # perform operations
    ...

3. Logging – use the logging module to record important information.

import logging

def my_function():
    logging.debug("进入函数")
    # perform operations
    ...

4. Breakpoint debugger – employ Python debuggers like pdb or ipdb to set breakpoints and step through code.

import pdb

def my_function():
    # set breakpoint
    pdb.set_trace()
    # perform operations
    ...

5. Runtime traceback – use the traceback module to print detailed error traces.

import traceback

try:
    result = 10 / 0
except ZeroDivisionError:
    traceback.print_exc()

6. Combine assertions and logging for richer debugging information.

import logging

def my_function(x):
    assert x > 0, "x 必须大于 0"
    logging.debug("进入函数")
    # perform operations
    ...

7. Proper exception handling – consistently catch and handle errors to keep programs stable.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("除零错误发生")

8. Unit testing – write tests with unittest to verify code correctness.

import unittest

def my_function(x):
    # perform operations
    ...

class MyFunctionTestCase(unittest.TestCase):
    def test_my_function(self):
        result = my_function(10)
        self.assertEqual(result, expected_result)

if __name__ == "__main__":
    unittest.main()

9. Performance profiling – use tools like cProfile or line_profiler to identify bottlenecks.

import cProfile

def my_function():
    # perform operations
    ...

cProfile.run("my_function()")

10. Code review – have peers review code to spot errors and improve quality.

通过让其他人审查你的代码来发现潜在的错误和改进机会,以提高代码质量和可靠性。

By applying these exception handling and debugging techniques, developers can more easily locate and fix errors, leading to higher code quality and maintainability.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Exception Handlingprogramming-fundamentalserror-handling
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

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.