Function std.exception.handle
Handle exceptions thrown from range primitives.
Use the RangePrimitive
enum to specify which primitives to handle.
Multiple range primitives can be handled at once by using the OR
operator
or the pseudo-primitives
and RangePrimitive.access
.
All handled primitives must have return types or values compatible with the
user-supplied handler.
RangePrimitive.pop
Prototype
auto handle(E, std.exception.RangePrimitive primitivesToHandle, alias handler, Range)( Range input ) if (isInputRange!Range);
Parameters
Name | Description |
---|---|
E | The type of Throwable to handle. |
primitivesToHandle | Set of range primitives to handle. |
handler | The callable that is called when a handled primitive throws a
Throwable of type E . The handler must accept arguments of
the form E, ref IRange and its return value is used as the primitive's
return value whenever E is thrown. For opIndex , the handler can
optionally recieve a third argument; the index that caused the exception. |
input | The range to handle. |
Returns
A wrapper struct
that preserves the range interface of
.
input
opSlice
Infinite ranges with slicing support must return an instance of
std.range.Take when sliced with a specific lower and upper
bound (see std.range.primitives.hasSlicing
);
deals with
this by handle
take
ing 0 from the return value of the handler function and
returning that when an exception is caught.
Example
import std.algorithm : equal, map, splitter; import std.conv : to, ConvException; auto s = "12,1337z32,54,2,7,9,1z,6,8"; // The next line composition will throw when iterated // as some elements of the input do not convert to integer auto r = s.splitter(',').map!(a => to!int(a)); // Substitute 0 for cases of ConvException auto h = r.handle!(ConvException, RangePrimitive.front, (e, r) => 0); assert(h.equal([12, 0, 54, 2, 7, 9, 0, 6, 8]));
Example
import std.algorithm : equal; import std.range : retro; import std.utf : UTFException; auto str = "hello\xFFworld"; // 0xFF is an invalid UTF-8 code unit auto handled = str.handle!(UTFException, RangePrimitive.access, (e, r) => ' '); // Replace invalid code points with spaces assert(handled.equal("hello world")); //front
is handled, assert(handled.retro.equal("dlrow olleh")); // as well asback
Authors
Andrei Alexandrescu and Jonathan M Davis