In this article, we will see different ways to extract the name of an exception that was caught in Python. Getting the name of the exception is very important to further debug the code and identify the actual issue.
Using type() function
We can use the type() function to get the name of the exception caught
Following the example:
def catch_exception():
try:
# Code that may raise an exception
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
print("Result:", result)
except Exception as e:
# Exception handling code
exception_name = type(e).__name__
print("Caught exception:", exception_name)
catch_exception()
Let’s first catch the exception using the try-except block. In the catch block use thetype()
function to obtain the exception type.
From the exception_type, extract the name of the exception.
Leave a Comment