
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Capture and Print Python Exception Message
In Python, you can capture and print exception messages using try and except blocks in multiple ways, such as -
- Using the as keyword
- Using the type() function
- Using the traceback module
Exception messages provide details about what went wrong, which is helpful for debugging and error handling.
Using the 'as' Keyword
You can assign the exception to a variable using the as keyword inside the except block. This allows you to access and print the actual error message.
Example: Capturing ZeroDivisionError message
In this example, we divide a number by zero and print the exception message -
try: result = 10 / 0 except ZeroDivisionError as e: print("Exception message:", e)
We get the following output -
Exception message: division by zero
Using print() and type() Functions with Exception
You can also use the type() function to get the type of exception and the print() function to display both the type and the message for better debugging.
Example: Displaying type and message
In this example, we try to access an undefined variable, which raises a NameError -
try: print(x) except Exception as e: print("Error type:", type(e).__name__) print("Error message:", e)
The output will be -
Error type: NameError Error message: name 'x' is not defined
Using traceback Module
Python's traceback module gives more detailed information, including the exact line where the error occurred, which helps in debugging complex programs.
Example
In this example, we import traceback module in Python and print the full stack trace -
import traceback try: a = 5 / 0 except Exception as e: print("Exception message:", e) traceback.print_exc()
The output includes the exception message and the traceback -
Exception message: division by zero Traceback (most recent call last): ... ZeroDivisionError: division by zero
Storing Exception Message in a Variable
You can also store the exception message in a variable if you want to use it later in your code, such as logging or displaying it to users.
Example: Storing and using exception message
In this example, we store the message and use it to build a user-friendly output -
try: int("abc") except ValueError as e: error_msg = str(e) print("An error occurred:", error_msg)
We get the following output -
An error occurred: invalid literal for int() with base 10: 'abc'