When Python encounters an error, it produces a treasure trove of error information called the traceback. The traceback includes the error message, the line number of the line that caused the error, and the sequence of the function calls that led to the error. This sequence of calls is called the call stack. Open a new file editor window in IDLE, enter the following program, and save it as error.py
def spam():
bacon()
def bacon():
raise Exception('This is the error message.')
spam()
When you run error.py, the output will look like this
Traceback (most recent call last):
File "/home/tommi087/Desktop/Development/code/phase-3/Automatingstuff/debugging/ErrorExample.py", line 6, in <module>
spam()
File "/home/tommi087/Desktop/Development/code/phase-3/Automatingstuff/debugging/ErrorExample.py", line 2, in spam
bacon()
File "/home/tommi087/Desktop/Development/code/phase-3/Automatingstuff/debugging/ErrorExample.py", line 4, in bacon
raise Exception('This is the error message.')
Exception: This is the error message.
The traceback is displayed by Python whenever a raised exception goes unhandled. But you can also obtain it as a string by calling traceback.format_exc(). This function is useful if you want the information from an exception’s traceback but also want an except statement to gracefully handle the exception. You will need to import Python’s traceback module before calling this function. For example, instead of crashing your program right when an exception occurs, you can write the traceback information to a log file and keep your program running. You can look at the log file later when you’re ready to debug your program. Enter the following into a new file called errorExample.py:
import traceback
try:
raise Exception('This is the error message.')
except:
errorFile = open('errorInfo.txt', 'w')
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback info was written to errorInfo.txt.')
This will be the output when the file is executed.
The traceback info was written to errorInfo.txt.
Top comments (1)
Most what spam apps today are designed to provide a seamless and effortless user experience. They offer features like one-tap blocking, easy integration with contacts, and even settings to prioritize certain types of calls over others. Many whatspam apps also allow users to enable silent notifications for blocked calls, so the app works silently in the background without interrupting the user’s day. This smooth, user-friendly experience is one of the reasons whatspam apps have become so popular, as they offer strong protection without requiring much effort from users.