`finally` is redundant?

Chris Wright via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 21 08:35:25 PST 2015


On Sat, 21 Nov 2015 11:15:22 +0530, Shriramana Sharma wrote:

> The page http://dlang.org/exception-safe.html says:
> 
> "It's try-finally that becomes redundant."
> 
> IIUC this is because we have scope(exit).
> 
> Does this mean that `finally` should eventually be removed from the
> language?

It's not necessarily the case that a feature should be removed from the 
language merely because it could be replicated with other features. We 
have structs, for instance, and we could use them to implement classes 
(albeit with a fair bit of pain).

In order to remove "finally" from the language, someone would have to sit 
down and analyze how much code it would break, how to fix it, and whether 
the fix is more readable and intuitive than the current version. Then 
they'd have to champion this change to the language designers -- 
primarily Walter. Nobody has chosen to do that as yet, so removing 
"finally" isn't on the table.

The main thing that try/finally gives you that scope guards generally 
don't is that the finally block executes immediately after the try block 
(or except block if it's there and an exception was thrown). For example:

---
auto tx = db.beginTransaction;
try {
  exportToJson(db.select("* FROM Users"));
} finally {
  tx.close;
}
db.dropTable("Users");
---

Here, we want to ensure that we export a consistent snapshot of the Users 
table, so we use a transaction. And let's say our hypothetical database 
will refuse to drop the table if there's an open transaction.

How would I replicate this with scope guards?

---
{
  auto tx = db.beginTransaction;
  scope (exit) tx.close;
  exportToJson(...);
}
db.dropTable("Users");
---

Is this version better? Well, during code review, I can more quickly see 
that the transaction won't be left open. But every other time I'm reading 
the method, I'm dealing with the fact that the statements shown are 
executed in a different order than I read them in. Plus I have to spend 
extra thought on scope in order to determine what the function does.

(That's part of the reason it's nice to forbid shadowing declarations. 
When I'm reading something that compiles, I can pretend that variables 
are in scope from declaration until the end of the function, which means 
less worrying about scope.)

So it's a bit of a toss-up at best. I'd expect a conservative decision if 
you pushed a D Improvement Proposal far enough to get a ruling.


More information about the Digitalmars-d-learn mailing list