nothrow and std.exception.ifThrown
Meta
jared771 at gmail.com
Fri Apr 30 14:03:51 UTC 2021
On Thursday, 29 April 2021 at 20:00:23 UTC, novice2 wrote:
> i dont understand why (templates too dificult for me yet),
> but if i comment "lazy" from T2,
> then compiler allow add "nothrow" to "ifThrown"
>
> ```d
> CommonType!(T1, T2) ifThrown(E : Throwable = Exception, T1,
> T2)(lazy scope T1 expression, /*lazy*/ scope T2 errorHandler)
> nothrow
> ```
> https://run.dlang.io/is/KTdd3G
This is because marking a function parameter as `lazy` is just
syntax sugar for the following:
```
CommonType!(T1, T2) ifThrown(E: Throwable = Exception, T1,
T2)(scope T1 delegate() expression, scope T2 delegate()
errorHandler);
string def = "some string";
auto s = format("%d", x).ifThrown({ return def; });
```
Behind the scenes, a `lazy` parameter is not really a value -
it's a function that _returns_ a value. The problem is that this
function is not `nothrow`, and can't be marked as such (this is
arguably a gap in the language). Removing `lazy` changes
`errorHandler` to be a plain old value again - which cannot throw
an exception, of course - so `ifThrown` can be marked `nothrow`.
However, you lose all the benefits of `errorHandler` being lazily
computed.
More information about the Digitalmars-d-learn
mailing list