[Python-ideas] Arguments to exceptions

Steven D'Aprano steve at pearwood.info
Tue Jul 4 20:58:33 EDT 2017


On Tue, Jul 04, 2017 at 05:08:57PM -0700, Ken Kundert wrote:
> On Tue, Jul 04, 2017 at 04:54:11PM -0400, Terry Reedy wrote:
> > There have been many proposals for what we might call
> > RichExceptions, with more easily access information.  But as Raymond
> > Hettinger keeps pointing out, Python does not use exceptions only
> > for (hopefully rare) errors.  It also uses them as signals for flow
> > control, both as an alternative form for alternation and for
> > iteration.  Alternation with try:except instead of if:else is
> > common.  In the try: unicode example above, the NameError is not an
> > error.  Until 2.2, IndexError served the role of StopIteration
> > today, and can still be used for iteration.  For flow control,
> > richer exceptions just slow code execution.
> 
> Terry,
>     Correct me if I am wrong, but this seems like an argument for the proposal.
> Consider the NameError, currently when raised the error message must be
> constructed before it is passed to the exception. But in the proposal, you
> simply pass the name (already available) and the format string (a constant). The
> name is never interpolated into the format string unless the message is actually
> used, which it would not in the cases you cite.

Terry's argument is that when used for flow control, you don't care what 
the index is. You just raise IndexError("index out of bounds") or 
similar.

Or for that matter, just raise IndexError(), as generators usually raise 
StopIteration() with no arguments.


-- 
Steve


More information about the Python-ideas mailing list