Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Get Python Exception Text



When something goes wrong in Python, it shows a message called exception text that explains the error. You can save and use this text in your program to help with logging or fixing the problem later.

You can get Python exception text using str() function, traceback module, logging, or the args attribute. This allows you to log, debug, or display user-friendly error messages in your programs.

Using str() Function

The easiest way to get the exception text is by converting the exception object to a string using the str() function. This returns the error message associated with the exception.

Example

In this example, we are dividing a number by zero and print the exception text using the str() function -

try:
   x = 1 / 0
except ZeroDivisionError as e:
   print("Exception text:", str(e))

We get the following output -

Exception text: division by zero

Using traceback Module

To get the complete traceback along with the exception message, you can use the traceback module. This is useful for debugging purposes.

Example

In this example, we print the entire traceback text using the traceback.format_exc() function -

import traceback

try:
   y = int("abc")
except ValueError:
   print("Full traceback:")
   print(traceback.format_exc())

The output contains the full exception details -

Full traceback:
Traceback (most recent call last):
  ...
ValueError: invalid literal for int() with base 10: 'abc'

Using logging Module

You can use the logging module to automatically log the exception text to a file or console.

Example

In this example, we use the logging.exception() function to capture the exception text -

import logging

logging.basicConfig(level=logging.ERROR)

try:
   open("missingfile.txt")
except FileNotFoundError:
   logging.exception("An error occurred:")

The output includes the full traceback logged by the logging system -

ERROR:root:An error occurred:
Traceback (most recent call last):
  ...
FileNotFoundError: [Errno 2] No such file or directory: 'missingfile.txt'

Using "e.args" Attribute

The exception object stores message arguments in the args attribute. You can get specific pieces of information using this.

Example: Accessing exception args

In this example, we print the tuple stored in the e.args attribute -

try:
   int("abc")
except ValueError as e:
   print("Exception args:", e.args)

The output shows the raw message in a tuple -

Exception args: ("invalid literal for int() with base 10: 'abc'",)
Updated on: 2025-05-26T13:36:24+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements