是D范围故障/成功/退出必要吗? [英] Is D's scope failure/success/exit necessary?
问题描述
当使用有try / catch / finally的语言时,D的失败/成功/退出范围声明仍然有用吗? D似乎没有终于可以解释为什么这些语句在D中使用。但像C#这样的语言是有用的吗?我正在设计一种语言,所以如果我看到很多优点,我会添加它。
When using a language that has try/catch/finally, are D's failure/success/exit scope statements still useful? D doesn't seem to have finally which may explain why those statements are used in D. But with a language like C# is it useful? I am designing a language so if I see many pros I'll add it in.
推荐答案
(X)
不是必要的,因为对于 c>不是必需的,只要
如果
和 goto
。
scope(X)
isn't necessary in the same way that for
isn't necessary provided you have if
and goto
.
这是我今天写的一些代码的例子: / p>
Here's a paraphrased example from some code I've been writing today:
sqlite3* db;
sqlite3_open("some.db", &db);
scope(exit) sqlite3_close(db);
sqlite3_stmt* stmt;
sqlite3_prepare_v2(db, "SELECT * FROM foo;", &stmt);
scope(exit) sqlite3_finalize(stmt);
// Lots of stuff...
scope(failure) rollback_to(current_state);
make_changes_with(stmt);
// More stuff...
return;
使用try / catch将此对比:
Contrast this to using try/catch:
sqlite3* db;
sqlite3_open("some.db", &db);
try
{
sqlite3_stmt* stmt;
sqlite3_prepare_v2(db, "SELECT * FROM foo;", &stmt);
try
{
// Lots of stuff...
try
{
make_changes_with(stmt);
// More stuff...
}
catch( Exception e )
{
rollback_to(current_state);
throw;
}
}
finally
{
sqlite3_finalize(stmt);
}
}
finally
{
sqlite3_close(db);
}
代码已变成 spaghetti ,传播整个商店的错误恢复,并强制一个级别的缩进每个try块。在我看来,使用范围(X)的版本明显更易读,更容易理解。
The code has turned into spaghetti, spreading the error recovery all over the shop and forcing a level of indentation for every try block. The version using scope(X) is, in my opinion, significantly more readable and easier to understand.
这篇关于是D范围故障/成功/退出必要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!