执行嵌套 TRY/FINALLY 语句的最佳实践 [英] Best practice to do nested TRY / FINALLY statement
问题描述
嵌套 try & 的最佳方法是什么?delphi 中的 finally 语句?
Hi What is the best way to do nested try & finally statements in delphi?
var cds1 : TClientDataSet;
cds2 : TClientDataSet;
cds3 : TClientDataSet;
cds4 : TClientDataSet;
begin
cds1 := TClientDataSet.Create(application );
try
cds2 := TClientDataSet.Create(application );
try
cds3 := TClientDataSet.Create(application );
try
cds4 := TClientDataSet.Create(application );
try
///////////////////////////////////////////////////////////////////////
/// DO WHAT NEEDS TO BE DONE
///////////////////////////////////////////////////////////////////////
finally
cds4.free;
end;
finally
cds3.free;
end;
finally
cds2.free;
end;
finally
cds1.free;
end;
end;
你能提出更好的方法吗?
Can you Suggest a better way of doing this?
推荐答案
以下内容如何:
var cds1 : TClientDataSet;
cds2 : TClientDataSet;
cds3 : TClientDataSet;
cds4 : TClientDataSet;
begin
cds1 := Nil;
cds2 := Nil;
cds3 := Nil;
cds4 := Nil;
try
cds1 := TClientDataSet.Create(nil);
cds2 := TClientDataSet.Create(nil);
cds3 := TClientDataSet.Create(nil);
cds4 := TClientDataSet.Create(nil);
///////////////////////////////////////////////////////////////////////
/// DO WHAT NEEDS TO BE DONE
///////////////////////////////////////////////////////////////////////
finally
freeandnil(cds4);
freeandnil(cds3);
freeandnil(cds2);
freeandnil(Cds1);
end;
end;
这会保持紧凑,并且只会尝试释放已创建的实例.确实没有必要执行嵌套,因为任何失败都会导致下降到 finally 并执行您提供的示例中的所有清理工作.
This keeps it compact, and only attempts to free the instances which were created. There really is no need to perform the nesting since ANY failure will result in dropping to the finally and performing all of the cleanup in the example you provided.
就我个人而言,我尽量不要嵌套在同一个方法中……除了 try/try/except/finally 场景.如果我发现自己需要嵌套,那么对我来说,这是考虑重构为另一个方法调用的好时机.
Personally I try not to nest within the same method... with the exception being a try/try/except/finally scenario. If I find myself needing to nest, then to me that is a great time to think refactoring into another method call.
EDIT 将对象创建更改为不引用应用程序,因为在此示例中不需要.
EDIT changed the object creation to not reference application, as its not necessary in this example.
这篇关于执行嵌套 TRY/FINALLY 语句的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!