DIP 1002 (TryElseExpression) added to the queue

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Wed Sep 28 16:40:44 PDT 2016


On 9/28/16 9:10 AM, pineapple wrote:
> I submitted a PR addressing some of the mentioned criticisms:
> https://github.com/dlang/DIPs/pull/46

Thanks. The Phobos examples compared:

(1)

// Current
unittest
{
     bool ok = true;
     try
     {
         auto r2 = assumeSorted([ 677, 345, 34, 7, 5 ]);
         debug ok = false;
     }
     catch (Throwable)
     {
     }
     assert(ok);
}
// With try/else
unittest
{
     try
     {
         auto r2 = assumeSorted([ 677, 345, 34, 7, 5 ]);
     }
     catch (Throwable)
     {
     }
     else assert(ok);
}
// Within existing D
unittest
{
     try
     {
         auto r2 = assumeSorted([ 677, 345, 34, 7, 5 ]);
     }
     catch (Throwable)
     {
         return;
     }
     assert(0);
}

(2)

// Current
     bool failed = false;
     try
     {
         auto d = c.get!(int);
     }
     catch (Exception e)
     {
         //writeln(stderr, e.toString);
         failed = true;
     }
     assert(failed); // :o)
// With try/else
     try
     {
         auto d = c.get!(int);
     }
     catch (Exception e)
     {
     }
     else
     {
         assert(0); // :o)
     }
// Within existing D
     assertThrown(c.get!(int));

(An argument here may be made that assertThrown is "cheating".)

(3)

// Current
void assertNot(string s)
{
     bool b = false;
     try { decode(s,DecodeMode.STRICT); }
     catch (DecodeException e) { b = true; }
     assert(b,s);
}

// With try/else
void assertNot(string s)
{
     try { decode(s,DecodeMode.STRICT); }
     catch (DecodeException e) {}
     else { assert(0, s); }
}
// With scope
void assertNot(string s)
{
     try { scope(success) assert(0, s); decode(s,DecodeMode.STRICT); }
     catch (DecodeException e) {}
}

The burden is to make the case that the try/else variant is better than 
the two others.


Andrei



More information about the Digitalmars-d mailing list