Coding⏱️ 2 min read📅 2026-05-31

How to Fix: How to get the name of an exception that was caught in Python?

Get the name of an exception caught in Python by accessing the exception object's __class__.__name__ attribute.

Quick Answer: Use `exception.__class__.__name__` to get the name of the exception.

To get the name of an exception that was caught in Python, you can use the `type()` function along with the `as` keyword when catching the exception. This will return the type of the exception as a string.

🛠️ Step-by-Step Verified Fixes

Method 1: Using `type()` function

  1. Step 1: Catch the exception using a variable name, and then use the `type()` function to get its type.

Example Code:

try: foo = bar except Exception as exception: name_of_exception = str(type(exception)) assert name_of_exception == 'Exception' print "Failed with exception [%s]" % name_of_exception

By using `str(type(exception))`, we can convert the type object to a string, which will display the name of the exception.

✨ Wrapping Up

In summary, to get the name of an exception that was caught in Python, you can use the `type()` function along with the `as` keyword when catching the exception. This will return the type of the exception as a string.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions