nothrow and std.exception.ifThrown
Meta
jared771 at gmail.com
Thu Apr 29 17:50:27 UTC 2021
On Thursday, 29 April 2021 at 16:02:20 UTC, novice2 wrote:
> Hello.
> I need use std.format.format() in nothrow function.
> format() can throw.
> For this case i have special default string.
> I don't want embrace format into try..catch block,
> and i found elegant std.exception.ifThrown.
> But DMD say "ifThrown not nothrow"
>
> https://run.dlang.io/is/kXtt5q
> ```d
> nothrow string foo(int x, string def) {
> import std.format: format;
> import std.exception: ifThrown;
>
> return format("%d", x).ifThrown(def);
> }
>
> Error: function std.exception.ifThrown!(Exception, string,
> string).ifThrown is not nothrow
> ```
>
> What i can use instead of ifThrown, or how it can be changed to
> nothrow?
> Thanks.
The reason for this, apparently, is in the definition of
`ifThrown`:
```
CommonType!(T1, T2) ifThrown(E : Throwable = Exception, T1,
T2)(lazy scope T1 expression, lazy scope T2 errorHandler) nothrow
```
It's not marked as `nothrow` in the function's definition, so
even if the delegate passed to ifThrown _is_ nothrow, the
compiler can't tell. There's no easy way around this that I can
think of OTOH that doesn't involve some effort on your part. One
thing you can do is wrap ifThrown with
`std.exception.assumeWontThrow`:
```
import std.exception: ifThrown, assumeWontThrow;
import std.functional: pipe;
alias ifThrown = pipe!(std.exception.ifThrown, assumeWontThrow);
nothrow string foo(int x, string def) nothrow {
import std.format: format;
return format("%d", x).ifThrown(def);
}
```
More information about the Digitalmars-d-learn
mailing list