anonymous functions and scope(exit)
Luis
Luis.panadero at gmail.com
Sat Jul 3 21:52:40 UTC 2021
On Saturday, 3 July 2021 at 17:47:47 UTC, Dennis wrote:
> On Saturday, 3 July 2021 at 17:20:47 UTC, Luis wrote:
>> scope(exit) inside of a anonymous functions, it's never called.
>
> I think the compiler infers the function `nothrow` since you
> don't throw any `Exception`, only an `Error`. Errors represent
> unrecoverable bugs, after which the program is in an invalid
> state, so the compiler is free to exit immediately without
> caring about destructors or `scope(exit)`. Use `Exception`
> instead of `Error` if you want the stack to properly unwind.
Indeed, this is happening.
I can reproduce with this :
```d
#!/usr/bin/env dub
/+ dub.sdl:
dependency "pijamas" version="~>1.1"
+/
import core.exception;
void main() {
import core.stdc.stdio;
import pijamas;
should(() {
printf("Hello\n");
scope(exit) printf("Bye\n");
throw new RangeError("bla bla");
}).Throw!RangeError;
auto f = () {
printf("Hello\n");
scope(exit) printf("Bye\n");
throw new RangeError("bla bla");
};
f();
}
```
Outputs this :
```
$ f.d
Hello
Hello
core.exception.RangeError at bla bla(20): Range violation
----------------
source/f.d:20 nothrow void f.main().__lambda2() [0x5647d46a17db]
source/f.d:22 _Dmain [0x5647d46a1732]
Program exited with code 1
```
If I change the RangeError, by a Exception, then the scope(exit)
it's executed.
More information about the Digitalmars-d-learn
mailing list