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.

Function std.exception.handle

Handle exceptions thrown from range primitives.

auto auto handle(E, RangePrimitive primitivesToHandle, alias handler, Range) (
  Range input
)
if (isInputRange!Range);

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 RangePrimitive.access and RangePrimitive.pop. All handled primitives must have return types or values compatible with the user-supplied handler.

Parameters

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

Note

Infinite ranges with slicing support must return an instance of std.range.Take when sliced with a specific lower and upper bound (see hasSlicing); handle deals with this by takeing 0 from the return value of the handler function and returning that when an exception is caught.

Example

import std.algorithm.comparison : equal;
import std.algorithm.iteration : 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.comparison : 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 as `back`

Authors

Andrei Alexandrescu and Jonathan M Davis

License

Boost License 1.0