Fundamentals 20 min read

Master Python Tracebacks: Decode Errors and Debug Like a Pro

This article explains what a Python Traceback is, how to read its information from bottom to top, lists common exception types such as AttributeError, ImportError, IndexError, and shows practical ways to record and handle errors using try/except and the logging module.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Tracebacks: Decode Errors and Debug Like a Pro

What is a Traceback?

Traceback is Python's error report, similar to a stack trace in other languages. When an exception occurs, Python prints a Traceback that shows the file, line number, and the code that caused the error.

# example.py

def greet(someone):
    print('Hello, ' + someon)

greet('Chad')

The above code raises a NameError because someon is undefined. The Traceback includes the file path, line number, and the exception type.

How to read a Python Traceback

Read the Traceback from bottom to top. The last line contains the exception type and message. The lines above show the call stack, with each File line indicating the file and line where the call originated.

Blue box : the final line with the error message.

Green box : the exception name and message.

Yellow box : the call stack, deeper calls appear higher.

Red underline : the actual code line that raised the exception.

Traceback diagram
Traceback diagram

Common Python exception types

AttributeError

Raised when an attribute reference or assignment fails.

a = 1
a.b

ImportError / ModuleNotFoundError

Raised when an import fails because the module or name does not exist.

import aaa

IndexError

Raised when a sequence index is out of range.

a_list = ['a', 'b']
a_list[3]

KeyError

Raised when a dictionary key is not found.

a_dict = {}
a_dict['b']

NameError

Raised when a name is not defined.

def greet(person):
    print(f'Hello, {persn}')

greet('World')

SyntaxError

Raised for invalid Python syntax.

def greet(person)
    pass

TypeError

Raised when an operation is applied to an object of inappropriate type.

1 + '1'

ValueError

Raised when a function receives an argument of correct type but inappropriate value.

a, b, c = [1, 2]

Recording and handling errors

Use try/except blocks to catch exceptions and prevent program termination.

import requests

url = "http://urlis233.com"
try:
    response = requests.get(url)
except requests.exceptions.ConnectionError:
    print("-1", "Link error, request failed")
else:
    print(response.status_code, response.text)

For production code, log exceptions with the logging module.

import logging, requests

logger = logging.getLogger(__name__)
url = "http://urlis233.com"

try:
    response = requests.get(url)
except requests.exceptions.ConnectionError as e:
    logger.exception(e)
    print(-1, "Link error, request failed")
else:
    print(response.status_code, response.content)

Understanding Tracebacks and common exception types helps you debug Python programs efficiently.

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.

debuggingPythonloggingError Messagestraceback
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

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.