Try blocks are trying

Greg Strong mageofmaple at protonmail.com
Sun Oct 10 16:53:14 UTC 2021


On Sunday, 10 October 2021 at 16:12:31 UTC, Carl Sturtivant wrote:
> Why is it that a try block is defined to establish a scope?
>
> ```
>     try {
>         auto x = frgl();
>     }
>     // ...
>     // x undefined here
>
> ```
> What is the benefit of this? If try (like static if/foreach) 
> did NOT establish a scope, then this annoyance would go away. 
> And if a scope was desired for some reason, then an extra pair 
> of braces could be written within.
>
> Right now rewriting the above requires getting the return type 
> of frgl and declaring x to be of that type before the try block.
>
> Design error?

One of the main reasons to use a try block is to ensure a 
destructor is called at the end of the try block.  If try didn't 
create a new scope, these things don't go out of scope, so they 
wouldn't be cleaned up.


More information about the Digitalmars-d mailing list