[Python-ideas] except expression
Chris Angelico
rosuav at gmail.com
Tue Feb 18 03:08:52 CET 2014
On Tue, Feb 18, 2014 at 12:31 PM, Ron Adam <ron3200 at gmail.com> wrote:
> To me, the added information on exceptions, should also be usable,
> preferable to allow more control on catching exceptions.
>
> For example:.
>
> value = expr1 except IndexError from foo: expr2
>
> Where the exception caught is one raised in "foo". While other IndexError's
> are allowed to bubble out.
>
> We can't use else... although that would be my first choice if else wasn't
> already used differently in except and for statements.
>
> To explain a bit further, when you get a trace back from an uncaught
> exception, the last line of the trace back contains the function it happened
> in. But that info is difficult to get from a caught exception.
> It's even nicer to be able to use it to specify more precisely what
> exceptions to catch.
I'd say that that's tangential to this proposal. Let's look at that in
terms of the statement try/except:
# Catch everything and swallow it
try: foo()
except: pass
# Catch everything and reraise it (pretty useless actually)
try: foo()
except: raise
# Catch based on class:
try: foo()
except IndexError: pass
except: pass # This bit is implicitly done, if you like
# Catch based on something else:
try: foo()
except Exception as e:
if e.foo: pass
else: raise
except: raise
It does make sense to be able to, for instance:
# Catch based on something else:
try: foo()
except IndexError as e if e.key<30: pass
One advantage of the currently-favoured syntax for exception
expressions is that it'd be easy to add extra syntax to both statement
and expression forms, since they're identical (modulo the "try:" at
the beginning). So if someone wants to propose any of these
hypothetical features, they'd fit fine into the expression version
too:
try: foo()
except as e: pass # Catch everything, and capture the exception
try: foo()
except OSError not FileNotFoundError: pass # Don't ignore FileNotFound
except Exception as e:
# log the exception, which might be several lines of code
try: foo()
except collections.Callable and collections.Iterable as e:
# Deal with... exceptions that are both callable and iterable?!??
Okay, so that last one is a bit stupid, but you get the idea. Same
thing would work in either context, so it can be raised (pun intended)
as a separate proposal.
ChrisA
More information about the Python-ideas
mailing list