void main() {
foo(1);
}
void foo(int i) nothrow {
assert(i < 0);
return i;
}
Compiles in release mode because asserts are disabled. When asserts are enabled, compilation fails w/ the following error msg:
test.d|5|function test.foo 'foo' is nothrow yet may throw
Fixing this is necessary to allow some code that doesn't throw any "real" exceptions, but uses asserts for internal consistency checks, to compile in debug mode. Also, if asserts are used in the precondition block instead of in the body, then the code compiles:
void foo(int i) nothrow
in {
assert(i < 0);
} body {
return i;
}
Comment #1 by braddr — 2009-01-26T02:58:33Z
Counter point.. how would one unit test proper assertions should they become non-catchable? For example:
void foo(int i) {
assert(i != 3, "don't ask me why, but 3 is illegal");
}
unittest {
try {
foo(3);
assert(false, "should not have reached here");
} catch (AssertError e) {
assert(e.msg() == "don't ask me why, but 3 is illegal");
}
}
(typed on the fly, so forgive any minor errors and worry about the desired behavior)
Comment #2 by dsimcha — 2009-01-26T07:46:23Z
Well, IMHO, asserts are supposed to be for pre- and postconditions and internal consistency checks and are essentially tests in themselves. Unittesting the asserts, then, is just plain overkill. If it's the kind of thing were it's more than just a sanity check, then you probably should be using "real" exceptions anyhow. Honestly, I've heard of people testing for "regular" exceptions being thrown when they should be, but never asserts.
Comment #3 by clugdbug — 2009-01-26T08:33:48Z
David - I agree with Brad. Sometimes the assertion in a precondition can be quite complicated. I've occasionally inserted tests to check it.
(A precondition in a LIBRARY function is a test for USER code. Not a test for the library code).
However, as I see it, asserts are basically a debugging feature. So they shouldn't interfere with nothrow.
I wonder if assert could be made unrecoverable inside a nothrow function?
IE, compiles to d_assert_nothrow()
which tests the condition, and immediately quits if it is not met?
Since assert() is magical already.
Comment #4 by dsimcha — 2009-01-26T08:58:24Z
Yes, but what makes this bug even more ridiculous (take another look at the original report) is that asserts only interfere w/ nothrow if they're in the body of the function. If they're in the precondition block, then they don't.
Comment #5 by smjg — 2009-01-27T19:43:01Z
ISTM the optimisations brought about by nothrow should be enabled only in release mode. So it would still be possible to catch the assert errors for testing purposes.