The OpenD Programming Language

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. T enforce(T value, const(char)[] msg, string file, size_t line)
    template enforce(E : Throwable = Exception)
    T
    enforce
    (
    T
    )
    (,
    lazy const(char)[] msg = null
    ,
    string file = __FILE__
    ,
    size_t line = __LINE__
    )
    if ()
    if (
    is(typeof(new E("", string.init, size_t.init)) : Throwable) ||
    is(typeof(new E(string.init, size_t.init)) : Throwable)
    )
  2. T enforce(T value, Dg dg)
  3. T enforce(T value, Throwable ex)

Members

Functions

enforce
T enforce(T value, const(char)[] msg, string file, size_t line)

Parameters

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.

file

The source file of the caller.

line

The line number of the caller.

Return Value

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