View source code
Display the source code in std/exception.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
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.

Template std.exception.enforce

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

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


Function enforce

Function enforce


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.


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


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


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")));


writeln(enforce(123)); // 123

    enforce(false, "error");
catch (Exception e)
    writeln(e.msg); // "error"
    writeln(e.file); // __FILE__
    writeln(e.line); // __LINE__ - 7


Alias your own enforce function

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


Andrei Alexandrescu and Jonathan M Davis


Boost License 1.0