Getting the exception value in Python Getting the exception value in Python python python

Getting the exception value in Python


use str

try:    some_method()except Exception as e:    s = str(e)

Also, most exception classes will have an args attribute. Often, args[0] will be an error message.

It should be noted that just using str will return an empty string if there's no error message whereas using repr as pyfunc recommends will at least display the class of the exception. My take is that if you're printing it out, it's for an end user that doesn't care what the class is and just wants an error message.

It really depends on the class of exception that you are dealing with and how it is instantiated. Did you have something in particular in mind?


Use repr() and The difference between using repr and str

Using repr:

>>> try:...     print(x)... except Exception as e:...     print(repr(e))... NameError("name 'x' is not defined")

Using str:

>>> try:...     print(x)... except Exception as e:...     print(str(e))... name 'x' is not defined


Even though I realise this is an old question, I'd like to suggest using the traceback module to handle output of the exceptions.

Use traceback.print_exc() to print the current exception to standard error, just like it would be printed if it remained uncaught, or traceback.format_exc() to get the same output as a string. You can pass various arguments to either of those functions if you want to limit the output, or redirect the printing to a file-like object.


matomo