Interview question
How does Python's traceback help you debug errors? Python का traceback errors debug करने में कैसे मदद करता है?
Answer
A traceback shows the exact sequence of function calls that led to an unhandled exception, read from top (where execution started) to bottom (where the error actually occurred).
def divide(a, b):
return a / b
def calculate(x, y):
return divide(x, y)
def main():
calculate(10, 0)
main()
# Traceback (most recent call last):
# File "script.py", line 8, in <module>
# main()
# File "script.py", line 7, in main
# calculate(10, 0)
# File "script.py", line 5, in calculate
# return divide(x, y)
# File "script.py", line 2, in divide
# return a / b
# ZeroDivisionError: division by zero
# READ BOTTOM-UP: the actual error type/message is at the very bottom,
# and each frame above shows the calling function that led there
# Programmatically inspecting a traceback
import traceback
try:
calculate(10, 0)
except ZeroDivisionError:
traceback.print_exc() # prints the full traceback without stopping execution
error_string = traceback.format_exc() # get traceback as a string, e.g. for logging
# Using logging instead of print for production error tracking
import logging
logging.basicConfig(level=logging.ERROR)
try:
calculate(10, 0)
except ZeroDivisionError:
logging.exception('Calculation failed') # logs the message AND full tracebackTraceback function calls की exact sequence दिखाता है जो unhandled exception तक ले गई, ऊपर (execution शुरू) से नीचे (जहां error हुआ) तक पढ़ी जाती है।
def divide(a, b):
return a / b
def calculate(x, y):
return divide(x, y)
def main():
calculate(10, 0)
main()
# Traceback (most recent call last):
# File "script.py", line 8, in <module>
# main()
# File "script.py", line 7, in main
# calculate(10, 0)
# File "script.py", line 5, in calculate
# return divide(x, y)
# File "script.py", line 2, in divide
# return a / b
# ZeroDivisionError: division by zero
# नीचे से ऊपर पढ़ें: actual error सबसे नीचे है
import traceback
try:
calculate(10, 0)
except ZeroDivisionError:
traceback.print_exc()
error_string = traceback.format_exc()
import logging
logging.basicConfig(level=logging.ERROR)
try:
calculate(10, 0)
except ZeroDivisionError:
logging.exception('Calculation failed')Was this answer clear?