Why am I getting inconsistent exceptions in Python?

In Python, I came across very strange behavior that is incompatible.

...
except IOError as msg:
    sys.exit("###ERROR IOError: %s" % (msg))

Normally this would get me a message like:

###ERROR IOError: [Errno 13] Permission denied: 'filename'

In the same cases, the above code gives me tupleinstead of the correct error message.

###ERROR IOError: (13, 'Permission denied')

This is very strange, because in all cases the exception comes from the same python method, codecs.open(...)

What makes me wonder about this is that if I delete the processing, the exception will reach the top levels with the correct text (full error message), always!

except IOError as msg:
    print(msg)
    raise msg

In the above example, the complete message will always be printed, for example IOError: [Errno 13] Permission denied: u'filename'.

Why this is happening and how I can prevent it, I do not want to provide users with incomplete error messages.

, .

, sys.exit(), print(msg) , sys.exit not.

+3
3

-, except Exc as e: raise e. raise . .

, sys.exit , , . ; tuple.

>>> print IOError(13, 'Permission denied')
[Errno 13] Permission denied
>>> print IOError((13, 'Permission denied'))
(13, 'Permission denied')

, , . , , , .

+5

Python 1.5 . , . .

, :

error = (13, 'Permision denied')

#more code

raise error

, , - :

raise IOError(error)
+1

, ; msg, , ; .

, msg.args "", .

0

Source: https://habr.com/ru/post/1763147/


All Articles