Function std.exception.ifThrown
ML-style functional exception handling. Runs the supplied expression
and
returns its result. If the expression
throws a Throwable
, runs the
supplied error handler instead and return its result. The error handler's
type must be the same as the expression
's type.
Prototypes
CommonType!(T1,T2) ifThrown(E, T1, T2)( T1 expression, T2 errorHandler ); CommonType!(T1,T2) ifThrown(E, T1, T2)( T1 expression, T2 delegate(E) errorHandler ); CommonType!(T1,T2) ifThrown(T1, T2)( T1 expression, T2 delegate(Exception) errorHandler );
Parameters
Name | Description |
---|---|
E | The type of Throwable s to catch. Defaults to Exception |
T1 | The type of the expression . |
T2 | The return type of the error handler. |
expression | The expression to run and return its result. |
errorHandler | The handler to run if the expression throwed. |
Returns
expression
, if it does not throw. Otherwise, returns the result of
errorHandler
.
Examples
//Revert to a default value upon an error: assert("x".to!int().ifThrown(0) == 0);
You can also chain multiple calls to ifThrown
, each capturing errors from the
entire preceding expression
.
Example
//Chaining multiple calls to ifThrown to attempt multiple things in a row: string s="true"; assert(s.to!int(). ifThrown(cast(int)s.to!double()). ifThrown(cast(int)s.to!bool()) == 1); //Respond differently to different types of errors assert(enforce("x".to!int() < 1).to!string() .ifThrown!ConvException("not a number") .ifThrown!Exception("number too small") == "not a number");
The expression
and the errorHandler
must have a common type they can both
be implicitly casted to, and that type will be the type of the compound
expression
.
Examples
//null and new Object have a common type(Object). static assert(is(typeof(null.ifThrown(new Object())) == Object)); static assert(is(typeof((new Object()).ifThrown(null)) == Object)); //1 and new Object do not have a common type. static assert(!__traits(compiles, 1.ifThrown(new Object()))); static assert(!__traits(compiles, (new Object()).ifThrown(1)));
If you need to use the actual thrown exception, you can use a delegate.
Example
//Use a lambda to get the thrown object. assert("%s".format().ifThrown!Exception(e => e.classinfo.name) == "std.format.FormatException");
Authors
Andrei Alexandrescu and Jonathan M Davis