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

How to Fix: When I catch an exception, how do I get the type, file, and line number?

Understand exception types and formatting in Python.

Quick Answer: Use the `type()` function to get the exception type, and `sys.exc_info()` or `traceback.format_exc()` to get the file name and line number.

When you catch an exception in Python, you can access information about the error using the `__traceback__` attribute of the exception object. This attribute contains a traceback object that provides information about the call stack at the time the exception occurred.

🔍 Why This Happens

  • [Cause]

🔧 Proven Troubleshooting Steps

Method 1: Extracting Traceback Information

  1. Step 1: Get the exception object and access its __traceback__ attribute.

Method 2: Formatting the Traceback

  1. Step 1: Use the traceback object to extract the error type, file name, and line number.

💡 Conclusion

To format the exception information into your desired output, you can use a combination of string formatting and the traceback object. For example:

import traceback as tb try: 4 / 0 except ZeroDivisionError as e: error_type = type(e).__name__ file_name = tb.extract_tb(e.__traceback__).fileno().decode('utf-8') line_number = tb.extract_tb(e.__traceback__).tb_lineno print(f'{error_type}, {file_name}, {line_number}')

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions