52

I want to work with the error message from an exception but can't seem to convert it to a string. I've read the os library man page but something is not clicking for me.

Printing the error works:

try:
    os.open("test.txt", os.O_RDONLY)
except OSError as err:
    print ("I got this error: ", err)

But this does not:

try:
    os.open("test.txt", os.O_RDONLY)
except OSError as err:
    print ("I got this error: " + err)

TypeError: Can't convert 'FileNotFoundError' object to str implicitly
dpetican
  • 771
  • 1
  • 5
  • 12

2 Answers2

97

In my experience what you want is repr(err), which will return both the exception type and the message.

str(err) only gives the message.

Jason C
  • 38,729
  • 14
  • 126
  • 182
Hendy Irawan
  • 20,498
  • 11
  • 103
  • 114
  • 1
    This is a much more useful answer, although it'll only work if you are doing debugging/don't already know what you're catching for. – Hansang May 12 '20 at 08:12
47

From the docs for print()

All non-keyword arguments are converted to strings like str() does and written to the stream

So in the first case, your error is converted to a string by the print built-in, whereas no such conversion takes place when you just try and concatenate your error to a string. So, to replicate the behavior of passing the message and the error as separate arguments, you must convert your error to a string with str().

miradulo
  • 28,857
  • 6
  • 80
  • 93