enforce

Enforces that the given value is true. If the given value is false, an exception is thrown. The

  • msg - error message as a string
  • dg - custom delegate that return a string and is only called if an exception occurred
  • ex - custom exception to be thrown. It is lazy and is only created if an exception occurred
  1. template enforce(E : Throwable = Exception)
  2. T enforce(T value, Dg dg)
    T
    enforce
    (
    T
    Dg
    string file = __FILE__
    size_t line = __LINE__
    )
    (,
    scope Dg dg
    )
    if (
    is(typeof(dg()))
    &&
    )
  3. T enforce(T value, Throwable ex)

Parameters

value T

The value to test.

dg 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.

Return Value

Type: T

value, if cast(bool) value is true. Otherwise, depending on the chosen overload, new Exception(msg), dg() or ex is thrown.

$(PANEL $(NOTE `enforce` is used to throw exceptions and is therefore intended to aid in error handling. It is $(I not) intended for verifying the logic of your program - that is what `assert` is for.) 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 $(I -release). )

If a delegate is passed, the safety and purity of this function are inferred from Dg's safety and purity.

Examples

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);
assertNotThrown(enforce(true, new Exception("this should not be thrown")));
assertThrown(enforce(false, new Exception("this should be thrown")));
assert(enforce(123) == 123);

try
{
    enforce(false, "error");
    assert(false);
}
catch (Exception e)
{
    assert(e.msg == "error");
    assert(e.file == __FILE__);
    assert(e.line == __LINE__-7);
}

Alias your own enforce function

import std.conv : ConvException;
alias convEnforce = enforce!ConvException;
assertNotThrown(convEnforce(true));
assertThrown!ConvException(convEnforce(false, "blah"));

Meta