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.assumeWontThrow
Wraps a possibly-throwing expression in a nothrow
wrapper so that it
can be called by a nothrow
function.
T assumeWontThrow(T)
(
lazy T expr,
string msg = null,
string file = __FILE__,
size_t line = __LINE__
) nothrow;
This wrapper function documents commitment on the part of the caller that
the appropriate steps have been taken to avoid whatever conditions may
trigger an exception during the evaluation of expr
. If it turns out
that the expression does throw at runtime, the wrapper will throw an
AssertError
.
(Note that Throwable
objects such as AssertError
that do not
subclass Exception
may be thrown even from nothrow
functions,
since they are considered to be serious runtime problems that cannot be
recovered from.)
Parameters
Name | Description |
---|---|
expr | The expression asserted not to throw. |
msg | The message to include in the AssertError if the assumption turns
out to be false. |
file | The source file name of the caller. |
line | The line number of the caller. |
Returns
The value of expr
, if any.
Example
import std .math : sqrt;
// This function may throw.
int squareRoot(int x)
{
if (x < 0)
throw new Exception("Tried to take root of negative number");
return cast(int) sqrt(cast(double) x);
}
// This function never throws.
int computeLength(int x, int y) nothrow
{
// Since x*x + y*y is always positive, we can safely assume squareRoot
// won't throw, and use it to implement this nothrow function. If it
// does throw (e.g., if x*x + y*y overflows a 32-bit value), then the
// program will terminate.
return assumeWontThrow(squareRoot(x*x + y*y));
}
writeln(computeLength(3, 4)); // 5
Authors
License
Copyright © 1999-2018 by the D Language Foundation | Page generated by ddox.