Try blocks are trying

FeepingCreature feepingcreature at gmail.com
Mon Oct 11 16:04:00 UTC 2021


On Monday, 11 October 2021 at 13:45:02 UTC, Paul Backus wrote:
> On Monday, 11 October 2021 at 09:27:30 UTC, FeepingCreature 
> wrote:
>> One possible solution would be a way to try/catch as an 
>> expression:
>>
>> ```
>> auto x = frgl().tryCatch(Exception exc: return exc;);
>> ```
>>
>> But D has no precedent for statements embedded in expressions 
>> like this, so it'd be a major language shift.
>
>
> ```
> import std.sumtype;
>
> SumType!(V, E) tryCatch(E, V)(lazy V expr)
> {
>     try return typeof(return)(expr);
>     catch (E e) return typeof(return)(e);
> }
>
> auto x = frgl().tryCatch!Exception;
> ```

Sure, but then you can't get at the `V` without - going into a 
subscope again. :) Though I guess it wouldn't be covered by a 
`try`.

Neat (my lang) doesn't have exceptions, but it does have built-in 
sumtypes with error marking, so you can have

```
(V | fail Exception) frgl() { ... }

auto x <- frgl();
```

And it will "pick" the non-fail `V` and, in the case of 
`Exception`, just propagate (return) it.

The goal is the same as `export try` - avoid having to define a 
variable in a separate block just to handle errors.


More information about the Digitalmars-d mailing list