Why does scope(success) have to use exceptions?
Andrej Mitrovic
andrej.mitrovich at gmail.com
Wed Jan 16 16:34:24 PST 2013
On 1/17/13, Era Scarecrow <rtcvb32 at yahoo.com> wrote:
> Obviously your code won't throw, however that's now how scope
> works. Only asserts or exceptions would/can manage to decide if the
> block was successful or not.
That's true for scope exit and scope failure, which need a
try/catch/finally. But if an exception is thrown the stack will
unwind, therefore the next statements won't be run, which is
interesting for scope(success).
Let's look at it this way:
void foo()
{
int x;
scope(success)
{
x = 1;
}
// < code which might throw >
x = 2;
}
try/catch version:
void foo()
{
int x;
try
{
x = 2;
// < code which might throw >
x = 1;
}
catch (Throwable e)
{
throw e;
}
}
But there's no need for a try/catch, you can rewrite this to:
void foo()
{
int x;
x = 2;
// < code which might throw >
x = 1; // if there's no stack unwind, this gets executed, hence
scope(success)
}
More information about the Digitalmars-d
mailing list