[Python-Dev] exception chaining
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
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.
> def smurfy(x):
> if x != 'magic flute':
> raise as WrongInstrument
> 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:
if x < 0:
raise as ValueError
elif x == 0:
raise as SpamError
elif x < 1:
raise as SmallerThanOneError
raise as RuntimeError
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:
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?
> Python-Dev mailing list
> Python-Dev at python.org
More information about the Python-Dev