1.5.2 for: else:

Martin Pool martinp at mincom.com
Wed Jul 28 22:45:13 EDT 1999


William Tanksley wrote:
> 
> On Tue, 27 Jul 1999 21:43:00 -0500, Gordon McMillan wrote:
> >William Tanksley wrote:
> >> On Tue, 27 Jul 1999 18:35:10 -0500, Gordon McMillan wrote:
> 
> >> >Maybe it violated your expectations, but it's much more valuable than
> >> >what you expected. After all, testing for an empty sequence is a
> >> >no-brainer. But finding a match in a list, and testing whether you
> >> >fell off the end without finding one, is (without the else clause) a
> >> >much messier proposal.

If nowhere else, I would have liked something like this in Java for
testing exception-handling code.  With this, I can write:

  >>> try:
  ...   print 0/0
  ... except ZeroDivisionError:
  ...   print "caught exception as expected"
  ... else:
  ...   print "Oops!  Exception didn't happen"

whereas in Java I have to write

  boolean caught = false;
  try {
    int a = 0 / 0;
  } catch (ArithmeticException a) {
    out.println("caught as expected");
    caught = true;
  } 
  if (!caught)
    out.print("exception didn't happen");

I doubt if I'll often use for: else or try: else, and perhaps they could
have clearer names, but I reckon they're nice to have.

-- 
 /\\\  Mincom | Martin Pool          | martinp at mincom.com
// \\\        | Software Engineer    | Phone: +61 7 3303-3333
\\ ///        | Mincom Ltd.          | 
 \///         | Teneriffe, Brisbane  | Speaking for myself only




More information about the Python-list mailing list