View source code Display the source code in std/exception.d from which this page was generated on github. Improve this page Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone. Page wiki View or edit the community-maintained wiki page associated with this page.

std.exception.enforce - multiple declarations

Function enforce

Enforces that the given value is true.

Prototype

T enforce(E, T)(
  T value,
  const(char)[] msg = null,
  string file = __FILE__,
  size_t line = __LINE__
)
if (is(typeof(()
{
if (!value)
{
}
}
)));

Parameters

NameDescription
value The value to test.
E Exception type to throw if the value evalues to false.
msg The error message to put in the exception if it is thrown.
file The source file of the caller.
line The line number of the caller.

Returns

value, if !value is false. Otherwise, new Exception(msg) is thrown.

Note

enforce is used to throw exceptions and is therefore intended to aid in error handling. It is not intended for verifying the logic of your program. That is what assert is for. Also, do not use enforce inside of contracts (i.e. inside of in and out blocks and invariants), because they will be compiled out when compiling with -release. Use assert in contracts.

Example

auto f = enforce(fopen("data.txt"));
auto line = readln(f);
enforce(line.length, "Expected a non-empty line.");

Function enforce

Enforces that the given value is true.

Prototype

T enforce(T, Dg, string file, ulong line)(
  T value,
  Dg dg
)
if (isSomeFunction!Dg && is(typeof(dg())) && is(typeof(()
{
if (!value)
{
}
}
)));

Parameters

NameDescription
value The value to test.
dg The delegate to be called if the value evaluates to false.
file The source file of the caller.
line The line number of the caller.

Returns

value if !value is false. Otherwise, the given delegate is called.

The safety and purity of this function are inferred from Dg's safety and purity.

Function enforce

Enforces that the given value is true.

Prototype

T enforce(T)(
  T value,
  Throwable ex
);

Parameters

NameDescription
value The value to test.
ex The exception to throw if the value evaluates to false.

Returns

value if !value is false. Otherwise, ex is thrown.

Example

auto f = enforce(fopen("data.txt"));
auto line = readln(f);
enforce(line.length, new IOException); // expect a non-empty line

Authors

Andrei Alexandrescu and Jonathan M Davis

License

Boost License 1.0

Comments