Re-raising exceptions with modified message

Gerard Flanagan grflanagan at yahoo.co.uk
Fri Jul 6 16:13:00 CEST 2007


On Jul 6, 12:18 am, Christoph Zwerschke <c... at online.de> wrote:
> Sorry for the soliloquy, but what I am really using is the following so
> that the re-raised excpetion has the same type:
>
> def PoliteException(e):
>      class PoliteException(e.__class__):
>          def __init__(self, e):
>              self._e = e
>          def __getattr__(self, name):
>              return getattr(self._e, name)
>          def __str__(self):
>              if isinstance(self._e, PoliteException):
>                  return str(self._e)
>              else:
>                  return '\n%s: %s, I am sorry!' % (
>                      self._e.__class__.__name__, str(self._e))
>      return PoliteException(e)
>
> try:
>      unicode('\xe4')
> except Exception, e:
>      raise PoliteException(e)

Would a decorator work here?


class PoliteException(Exception):
    def __init__(self, e):
        self._e = e
    def __getattr__(self, name):
        return getattr(self._e, name)
    def __str__(self):
        return '\n%s: %s, I am sorry!' % (
                    self._e.__class__.__name__, str(self._e))

def politefail(fn):
    def wrapper(*args, **kwargs):
        try:
            return fn(*args, **kwargs)
        except Exception, e:
            raise PoliteException(e)
    return wrapper

@politefail
def funktion():
     unicode('\xe4')

funktion()

@politefail
def raise_exception(err, *args):
    raise err(*args)


def funktion():
    if 1 != 2:
        raise_exception(ArithmeticError, '1 is not equal to 2.')

print
funktion()




More information about the Python-list mailing list