Assigning different Exception message

Peter Otten __peter__ at web.de
Thu Oct 12 09:32:25 EDT 2006


Tor Erik Soenvisen wrote:

>         try:
>             self.cursor.execute(sql)
>         except AttributeError, e:
>             if e.message == "oracleDB instance has no attribute 'cursor'":
>                 e.message = 'oracleDB.open() must be called before' + \
>                             ' oracleDB.query()'
>             raise AttributeError, e
> 
> This code does not re-assign e's message when the conditional is
> satisfied. Why not?

It does, but e.args is used to generate the message shown:

>>> try:
...     None.not_there
... except AttributeError, e:
...     e.args = ("whatever",)
...     raise e
...
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
AttributeError: whatever

However, I would prefer to rewrite your snippet along the lines:

try:
    cursor = self.cursor
except AttributeError:
    raise EriksCustomError("oracleDB.open()...")
else:
    cursor.execute(sql)

Peter




More information about the Python-list mailing list