[Python-Dev] exception chaining (original) (raw)

Steven D'Aprano steve at pearwood.info
Sat Jan 21 07:02:14 CET 2012


Ethan Furman wrote:

The question I have at the moment is: should raise as be an error if no exception is currently being handled?

I think so.

"raise as Spam" essentially means "raise Spam with the context set to None". That's actually only useful if the context otherwise wouldn't be None, that is, if you're raising an exception when another exception is active. Doing it "just in case" defeats the usefulness of exception chaining, and should be discouraged.

It is easier to change our minds later and allow "raise as" outside of an except block, than to change our minds and forbid it.

Example: def smurfy(x): if x != 'magic flute': raise as WrongInstrument dosomethingwithx If this is allowed then smurfy could be called from inside an except clause or outside it.

What's your use-case? The only one I can think of is this:

def choose_your_own_exception(x): if x < 0: raise as ValueError elif x == 0: raise as SpamError elif x < 1: raise as SmallerThanOneError else: raise as RuntimeError

try: something() except TypeError: choose_your_own_exception(x)

I don't think we want to encourage such practices. Besides, if you really need such an exception selector, change every "raise as" to return, then do:

try: something() except TypeError: raise as choose_your_own_exception(x)

Much more clear.

I don't care for it for two reasons:

- I don't like the way it looks - I can see it encouraging always using raise as instead of raise and losing the value of exception chaining. Other thoughts? Ethan


Python-Dev mailing list Python-Dev at python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/steve%40pearwood.info



More information about the Python-Dev mailing list