scope(failure) - Programming in D, doesn't catch throw. When should scope (failure) be used?
kdevel
kdevel at vogtner.de
Wed Nov 26 20:06:19 UTC 2025
On Wednesday, 26 November 2025 at 18:42:16 UTC, Brother Bill
wrote:
> I would expect if that is so, then the program shouldn't crash.
>
> If this is correct, when should scope(exit), scope(success) and
> scope(error) be used, if ever?
Though it is not correct the scope exit clauses should be used
for cleanup. Not for anything that may throw itself.
```d
import std;
enum Op { pass, fail }
int worker (Op op)
{
scope (exit)
writeln ("worker exit: op = ", op);
writeln ("worker entry: op = ", op);
final switch (op) {
case Op.pass:
return 0;
case Op.fail:
throw new Exception ("failing...");
}
}
int doit (string [] args)
{
scope (exit) writeln ("scope exit");
scope (success) writeln ("scope success");
scope (failure) writeln ("scope failure");
enforce (args.length == 2, format ("usage: %s (pass|fail)",
args [0]));
auto op = args [1].to!Op;
return worker (op);
}
int main (string [] args)
{
try return doit (args);
catch (Exception e) stderr.writeln (e.msg);
return 1;
}
```
More information about the Digitalmars-d-learn
mailing list