collectException

Catches and returns the exception thrown from the given expression. If no exception is thrown, then null is returned and result is set to the result of the expression.

Note that while collectException can be used to collect any Throwable and not just Exceptions, it is generally ill-advised to catch anything that is neither an Exception nor a type derived from Exception. So, do not use collectException to collect non-Exceptions unless you're sure that that's what you really want to do.

  1. T collectException(E expression, E result)
    T
    collectException
    (
    T = Exception
    E
    )
    (
    lazy E expression
    ,
    ref E result
    )
  2. T collectException(E expression)

Parameters

T

The type of exception to catch.

expression E

The expression which may throw an exception.

result E

The result of the expression if no exception is thrown.

Examples

int b;
int foo() { throw new Exception("blah"); }
assert(collectException(foo(), b));

version (D_NoBoundsChecks) {}
else
{
    // check for out of bounds error
    int[] a = new int[3];
    import core.exception : RangeError;
    assert(collectException!RangeError(a[4], b));
}

Meta