The most common method to catch and print the exception message in Python is using try-except statements. If You want to save an error message then use the logger.exception() method.
This method produces an error message as well as a log trace. It contains information such as the code line number at which the exception occurred and the time the exception occurred.
Python Print exception
Simple example code catch and prints The Exception Messages In Python.
list_arr = [10, 20, 30, "5f", "7k", 78, 88]
for elem in list_arr:
try:
print("Result: ", elem / 9)
except Exception as e:
print("Exception occurred for value '" + elem + "': " + repr(e))
Output:
Using try and logger.exception to print an error message
import logging
logger = logging.getLogger()
num1 = 1
num2 = 0
try:
print("Result: ", num1 / num2)
except Exception as e:
logger.exception("Exception Occured while code Execution: " + str(e))
Output:
Exception Occured while code Execution: division by zero
Traceback (most recent call last):
File "C:\Users\Rohit\PycharmProjects\pythonProject\modules\main.py", line 9, in <module>
print("Result: ", num1 / num2)
ZeroDivisionError: division by zero
Do comment if you have any doubts or suggestions on this Python exception-handling topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.