assert(expression, error)

Jonathan M Davis jmdavisProg at gmx.com
Sat Feb 12 05:44:26 PST 2011


On Saturday 12 February 2011 05:23:06 spir wrote:
> Hello,
> 
> Is there a way to specify what error to throw using (a variant of) assert:
>      assert(n > 0, new ValueError("..."));
> 
> (Sure, one can write:
>      if (n <= 0)
>          throw new ValueError("..."));
> but the same remark applies to plain assert: the whole point of assert is
> to have it as builtin feature with clear application field & well-known
> semantics, shared by the community of D programmers.)

You mean std.exception.enforce?

assert throws AssertError. Regardless, you probably shouldn't be creating new 
Error types generally. You're _not_ supposed to catch errors and try and handle 
them, so there really isn't any benefit in creating new Error types generally 
anyway. If you want to assert, use assert. Let it be AssertError.

If you want to throw a specific Exception type, and you want it to be a one-
liner, use enforce. Be aware, however, that enforce is lazy, so any function 
which uses it can't currently be inlined.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list