On 7/26/22 16:43, pascal111 wrote:
> In next example code, it used user-made exception,

I am not sure I understand you correctly because the program you show throws Exception, which is not user-made at all.

If you want to throw a particual exception that you define, you need to inherit that type from Exception.

The following program show an example as well as 'enforce', which I prefer over explicit if+throw+else:

import std.stdio;
import std.format;

class MissingArguments : Exception {
  this(string msg, string file = __FILE__, size_t line = __LINE__) {
    super(msg, file, line);
  }
}

void main(string[] args) {
  // if (args.length != 42) {
  //   throw new MissingArguments(args.length);
  // }

  import std.exception : enforce;
  enforce!MissingArguments(args.length == 42,
                           format!"Too few arguments: %s"(args.length));

  // Program continues here... (No 'else' needed.)
}

Ali

Reply via email to