D equivalent of Python's try..else

Russel Winder via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 21 01:35:33 PST 2015


On Fri, 2015-11-20 at 22:39 -0800, Ali Çehreli via Digitalmars-d-learn
wrote:
> 
[…]
> I don't know what idiom that enables in Python but it feels to me
> like 
> putting the statements right after the ones that could throw suffices
> in 
> D (and Python):

The else clause for while, for, try, has always been a bit of an
outlier bit of syntax, there as much for consistency with if as much as
anything else. It has not been taken out of the language for various
reasons, not least of which is that on some occasions it does make the
code more comprehensible.

> 
>      try {
>          may_throw();
>          may_throw2();
>          code_for_when_they_succeed();
> 
>      } catch (/* ... */) {
>          // ...
>      }

This is entirely true but in terms of meaning:

    try:
        may_throw()
    except ...:
        ...
    else:
       code_for_when_they_succeed()

makes it clear that there is a block where exception might occur and
this is what is being protected, and that the follow up code is not
being protected it is there as a non-exception tail to the code.
Arguable maybe, person maybe, but there are times when I really like
this separation.

else on for and while, whilst technically redundant as well, does
occasionally make for a nicer read, for very analogous reasons. It can
generally avoid the need for extra booleans and other state variables.

-- 
Russel.
=============================================================================
Dr Russel Winder      t: +44 20 7585 2200   voip: sip:russel.winder at ekiga.net
41 Buckmaster Road    m: +44 7770 465 077   xmpp: russel at winder.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: This is a digitally signed message part
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20151121/751120e3/attachment-0001.sig>


More information about the Digitalmars-d-learn mailing list