Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between wrapping a try-finally block with a try-except block and vice versa?

Are there any practical difference between the two coding patterns in Delphi:

Version 1

try
  try
    {Do something}
  finally
    {Do tidy up}
  end
except
  {Handle exception}
end;

Version 2

try
  try
    {Do something}
  except
    {Handle exception}
  end
finally
  {Do tidy up}
end;
like image 330
kludg Avatar asked Sep 16 '12 08:09

kludg


2 Answers

There are two differences:

  1. The relative order in which the except and finally blocks execute differs. In version 1, the finally executes before the except. In version 2 the excecution order is reversed.
  2. In version 1, if the finally block raises, then it will be handled by the except block. In version 2, if the finally block raises, then it will be handled by the next containing exception handler, i.e. outside this code.

Usually you aren't concerned about finally blocks that raise. You simply don't expect that to happen and if it does, something is probably very broken.

So the difference that counts is whether the finally runs before the exception handler, or vice versa. Sometimes it doesn't matter, but it often does make a difference.

like image 114
David Heffernan Avatar answered Sep 27 '22 21:09

David Heffernan


When you use try..except below lines executed.

Resource := TAbstractResource.Create;
try
  Resource.DoSomeThing;
except
  On E:Exception Do 
   HandleException(E);
end;
FreeAndNil(Resource);
like image 39
MajidTaheri Avatar answered Sep 27 '22 20:09

MajidTaheri