Why doesn't it work to add information to the exception message?

Why is this not working?

try: 1/0 except ZeroDivisionError as e: e.message += ', you fool!' raise 

A modified message is not used, even if it remains on the exception instance. Is there a working scheme for the above? The behavior should be similar to my current workaround below:

 try: 1/0 except ZeroDivisionError as e: args = e.args if not args: arg0 = '' else: arg0 = args[0] arg0 += ', you fool!' e.args = (arg0,) + args[1:] raise 

I know the exception chain in python3, it looks good, but unfortunately does not work in python2. So what is the usual recipe for recreating an exception in python2?

Note. Due to the warnings and cautions mentioned here , I don't want to dig up the trace and create a new exception, but rather raise an existing exception .

+6
source share
2 answers

Changing e.args is the only way to do this. The implementation for BaseException.__str__ only considers the args tuple, it does not look at message at all:

 static PyObject * BaseException_str(PyBaseExceptionObject *self) { PyObject *out; switch (PyTuple_GET_SIZE(self->args)) { case 0: out = PyString_FromString(""); break; case 1: out = PyObject_Str(PyTuple_GET_ITEM(self->args, 0)); break; default: out = PyObject_Str(self->args); break; } return out; } 

This should not be too unexpected since BaseException.message deprecated since Python 2.6.

+4
source

I don't think there will be a better solution than your workaround. ZeroDivisionError does not use the message property to construct its output, so changing it will have no effect.

If you specifically catch ZeroDivisionError, it should always have one argument, so the following more concise version will work:

 try: 1/0 except ZeroDivisionError as e: e.args = (e.args[0] + ', you fool!',) raise 

If you check the properties of ZeroDivisionError, all it has is args and message , and it does not use message to not create a new error, changing the arguments is almost the only possible solution.

0
source

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


All Articles