scope guards

Manu via Digitalmars-d digitalmars-d at puremagic.com
Sun Aug 3 08:28:35 PDT 2014


I'm trying to make better use of scope guards, but I find myself belting
out try/catch statements almost everywhere.
I'm rather disappointed, because scope guards are advertised to offer the
promise of eliminating try/catch junk throughout your code, and I'm just
not finding that to be the practical reality.

I think the core of the problem is that scope(failure) is indiscriminate,
but I want to filter it for particular exceptions. The other issue is that
you still need a catch() if you don't actually want the program to
terminate, which implies a try... :/

One thing that may be leveraged to eliminate most catch blocks is the
existing ability to return from scope guard blocks, allowing to gracefully
return from a function while unwinding, akin to a catch.
The problem then is that you can't handle specific exceptions.

I'm thinking this would make all the difference:

scope(failure, MyException e) // only executed for exceptions of type
MyException
{
  writeln(e.msg); // can refer to the exception in this failure block
  return failureValue; // and can gracefully return from the function too
}

That would eliminate about 80% of my try/catch blocks.
The remaining suffer from the problem where I want to respond to exceptions
NOT of a specific type, ie, clean up in the case of an unexpected/unknown
exception.

scope(failure, ~MyException)
{
  // clean up, because some unexpected exception occurred that I
don't/can't handle.
}


Is there already some mechanism to do this? I couldn't find anything in the
docs.
It seems like an obvious thing to want to do.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20140804/c6558ba5/attachment.html>


More information about the Digitalmars-d mailing list