Template std.exception.enforce
Enforces that the given value is true. If the given value is false, an exception is thrown. The
msg
- error message as astring
dg
- custom delegate that return a string and is only called if an exception occurredex
- custom exception to be thrown. It islazy
and is only created if an exception occurred
template enforce(E)
;
T enforce(T, Dg, string file = __FILE__, ulong line = __LINE__)
(
T value,
scope Dg dg
)
if (isSomeFunction!Dg && is(typeof(dg())) && is(typeof(()
{
if (!value)
{
}
}
)));
T enforce(T)
(
T value,
lazy Throwable ex
);
Template enforce
Contained Functions
Name | Description |
---|---|
enforce |
Function enforce
Function enforce
Parameters
Name | Description |
---|---|
value | The value to test. |
E | Exception type to throw if the value evaluates to false. |
msg | The error message to put in the exception if it is thrown. |
dg | The delegate to be called if the value evaluates to false. |
ex | The exception to throw if the value evaluates to false. |
file | The source file of the caller. |
line | The line number of the caller. |
Returns
value
, if cast(bool) value
is true. Otherwise,
depending on the chosen overload, new Exception(msg)
, dg()
or ex
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 invariant
s), because contracts are compiled out when
compiling with -release.
If a delegate is passed, the safety and purity of this function are inferred
from Dg
's safety and purity.
Example
import core .stdc .stdlib : malloc, free;
import std .conv : ConvException, to;
// use enforce like assert
int a = 3;
enforce(a > 2, "a needs to be higher than 2.");
// enforce can throw a custom exception
enforce!ConvException(a > 2, "a needs to be higher than 2.");
// enforce will return it's input
enum size = 42;
auto memory = enforce(malloc(size), "malloc failed")[0 .. size];
scope(exit) free(memory .ptr);
Example
assertNotThrown(enforce(true, new Exception("this should not be thrown")));
assertThrown(enforce(false, new Exception("this should be thrown")));
Example
writeln(enforce(123)); // 123
try
{
enforce(false, "error");
assert(false);
}
catch (Exception e)
{
writeln(e .msg); // "error"
writeln(e .file); // __FILE__
writeln(e .line); // __LINE__ - 7
}
Example
Alias your own enforce function
import std .conv : ConvException;
alias convEnforce = enforce!ConvException;
assertNotThrown(convEnforce(true));
assertThrown!ConvException(convEnforce(false, "blah"));