Try blocks are trying

Ali Çehreli acehreli at yahoo.com
Sun Oct 10 17:32:10 UTC 2021


On 10/10/21 9:12 AM, Carl Sturtivant wrote:
 > Why is it that a try block is defined to establish a scope?
 >
 > ```
 >      try {
 >          auto x = frgl();
 >      }
 >      // ...
 >      // x undefined here
 >
 > ```

One more point in favor of the current semantics, which your code seems 
to be in support of: x may be left in a state that does not provide its 
invariants.

I am thinking out loud now: Luckily (and of course by good design), 
scope(failure) cannot be used in bad state either because in that case x 
must have already been defined when the scope(failure) appears in code:

   scope(failure) {
     writeln(x);  // Compilation error (undefined x)
   }
   auto x = frgl();

And the following does not execute the scope(failure) block if frgl() 
throws because scope(failure) code is not "registered" yet:

   auto x = frgl();
   scope(failure) {
     writeln(x);  // Not executed if frgl() throws
   }

Ok, I think we are in good shape with scope(failure) as well. :)

Ali



More information about the Digitalmars-d mailing list