In this article we will show you the solution of python get exception message, Python has a wide range of functionality for handling exceptions. An exception event stops a programme from working and, if it is not handled, ends it immediately.
The ValueError, TypeError, and IndexError are the most well-known instances.
Your programme will end instantly if there is an exception. To prevent this, you can place a try/except block around the code where you anticipate that a certain exception would occur to catch the exception.
This is how to recognise and print a specific exception:
When an exception occurs in a piece of code, it should be caught and printed by enclosing it in an indented try block and then using the command "except Exception as e" to preserve the exception's message in the string variable e.
The error message can now be printed with "print(e)" or used for additional processing.
We will now discuss the idea of how to get an exception message in python with an example.
Step By Step Guide On Python Get Exception Message :-
Code 1
import logging logger=logging.getLogger() num1=int(input("Enter no 1:")) num2=int(input("Enter no 2:")) try: print("Result: ", num1/num2) except Exception as e: logger.exception("Exception Occured while code Execution: "+ str(e))
Code 2
# Creating an empty list new_list =[] n = int(input("TC Example Of Enter number of elements : ")) for i in range(n): try: item = int(input()) # Add the item in the list new_list.append(item) except: print("Invalid Input!") print("Next entry.") print("The list entered by user is: ", new_list)
- For logging failures and exceptions, the "logging" module is imported.
- The command "logger=logging.getLogger()" returns the root logger.
- "num1" and "num2" are two integers that the user enters.
- Any exceptions that arise when performing the division operation "num1/num2" are handled in a "try-except" block.
- The division operation is carried out and the outcome is printed inside the "try" block.
- The "except" block is carried out if an exception occurs.
- The exception object is converted to a string and the exception message is written to the log using the "logger.exception()" method.
- The console is printed with the logged message.
- Programme execution is completed.
Conclusion :-
As a result, we have successfully learned how to get an exception message in python with an example.
When an exception occurs in a piece of code, it should be caught and printed by enclosing it in an indented try block and then using the command "except Exception as e" to preserve the exception's message in the string variable e.
The error message can now be printed with "print(e)" or used for additional processing.
I hope this article on python get exception message helps you and the steps and method mentioned above are easy to follow and implement.