In many places in some Apps which I maintain , I've found code which uses a try/finally
or try/except
block in a for loop
or if
sentence avoiding the use of begin/end
Consider the next code (not production code, just a sample)
{$APPTYPE CONSOLE}
{$R *.res}
uses
Classes,
SysUtils;
Procedure TestNoBeginEnd;
var
i : Integer;
L1 : TStringList;
begin
for i := 1 to 10 do
try
L1:=TStringList.Create;
try
L1.Add('Bar');
L1.Add(IntToStr(i));
L1.Add('Foo');
finally
Writeln(L1.Text);
L1.Free;
end;
except
on E: Exception do
Writeln('Opps '+E.ClassName, ': ', E.Message);
end;
end;
begin
try
TestNoBeginEnd;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
The Question, Is considered a bad practice, code smell or exist any drawback using a try/finally or try/except instead of begin/end in delphi?
UPDATE
I'm sorry by the silly sample code, just for clarify the try/finally and try/except doesn't pretend replace the begin/end , just to avoid to use it (the begin/end) when exist a case when the use of the try/finally or the try/except doesn't requires a begin/ end.
I personally don't see the need to add the extra
begin..end
around atry..finally/except..end
, especially when there is little chance of code being added just before thetry
or certainly after theend
.That being said, the question would be more whether we need systematically a
begin..end
after a..do
or a..then
even when there is only a single instruction (in your case atry..
instruction).It's mostly a question of style and habit, some people prefer to code defensively and systematically put a begin..end, others try to avoid unnecessary lines as much as possible.
When a fair number of lines are involved, I tend to add the
begin..end
to make the scoping more obvious.I'd say, use good judgment and see what the chances are that someone (or you) modifying the code later could miss the intended scope.