tags:

views:

78

answers:

2

Here's my exception class that is using raise:

class SCE(Exception):
    """
    An error while performing SCE functions.
    """
    def __init__(self, value=None):
        """
        Message: A string message or an iterable of strings.
        """
        if value is None:
            self._values = []
        elif isinstance(value, str):
            self._values = [value]
        else:
            self._values = list(value)

    def __raise__(self):
        print('raising')
        if not len(self._values):
            return

    def __str__(self):
        return self.__repr__()

    def __iter__(self):
        return iter(self._values)

    def __repr__(self):
        return repr(self._values)

Currently if I raise this exception with no value I get traceback followed by:

__main__.SCE: []

Instead of what I expected which was:

raising
>>>

How do you overload raise?

A: 

There is no such special method __raise__ (at least none that I have ever heard of or that I can find in the Python documentation).

Why do you want to do this? I can't think of any reason why you want custom code be be executed when the exception is raised (as opposed to either when the exception is constructed, which you can do with the __init__ method, or when the exception is caught, which you can do with an except block). What is your use case for this behavior, and why do you expect that Python supports it?

Daniel Pryden
Link to documentation: http://docs.python.org/reference/datamodel.html
Felix Kling
Um... that page doesn't contain the string "__raise__"
Will McCutchen
@Will McCutchen: I think that's the point. If it's not in the docs, it doesn't exist, right?
Daniel Pryden
Haha, I'm an idiot. I originally read that as "Why don't you check the documentation at this link" and expected to be enlightened. Now I read it as "Why don't you helpfully link to this documentation?" Sorry!
Will McCutchen
+2  A: 

As the other answer says, there is no __raise__ special method. There was a thread in 2004 on comp.lang.python where someone suggested adding such a method, but I don't think there was any followup to that. The only way I can think of to hook exception raising is either by patching the interpreter, or some kind of source or bytecode rewriting that inserts a function call next to the raise operation.

mithrandi
ah, that's the same thread I saw then. I was like "hey why doesn't this work?". It said details soon and I figured 6 years was enough.
orokusaki