nothrow and std.exception.ifThrown

Ali Çehreli acehreli at yahoo.com
Thu Apr 29 17:52:25 UTC 2021


On 4/29/21 9:02 AM, novice2 wrote:

 > format() can throw.

In order to throw for an int, I added a foo(x) expression to prove that 
the code works.

 > I don't want embrace format into try..catch block,
 > and i found elegant std.exception.ifThrown.

There are collectException and collectExceptionMsg as well. The 
following code works for 42 and uses the default string "error" for 43.

int foo(int x) {
   import std.exception : enforce;
   enforce(x == 42, "some error");
   return x;
}

nothrow string foo(int x, string def) {
   import std.format: format;
   import std.exception: collectException;

   string result;
   auto exc = collectException(format("%d", foo(x)), result);
   return (exc is null) ? result : def;
}

void main() {
   import std.stdio: writeln;
   writeln(foo(42, "error"));
   writeln(foo(43, "error"));
}

Ali



More information about the Digitalmars-d-learn mailing list