Home > Enterprise >  How to extract information for python error output
How to extract information for python error output

Time:12-01

I am trying to extract the information for the code I am writing. For example, when I write this code:

code = "hello"
code[10]

the output I would get from python is as followed:

IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_24520/526779498.py in <module>
----> 1 code[10]

IndexError: string index out of range

But when I implement a try except loop on the code:

code  = "hello"

try:
    code[10]
except Exception as e:
    print(e)

my output only shows me:

string index out of range

What would I need to do in order to extract the text "IndexError". Also, if there are any libraries that are useful to extract python errors for logging please let me know as well. Thank you.

CodePudding user response:

You need to get the name attribute of the exception

code  = "hello"

try:
    code[10]
except Exception as e:
    print(type(e).__name__)

Output:

IndexError
  • Related