Forum > General

what is the point of finally in try finally end;

(1/2) > >>

dieselnutjob:
Comparing these to codes


--- Code: ---try
  trythisfunction;
finally
  alwaysdothisfunction;
end;

--- End code ---


--- Code: ---try
  trythisfunction;
finally
  ;
end;
alwaysdothisfunction;

--- End code ---

Don't they do exactly the same thing?

So what is the point of having a "finally" at all?

thanks, Philip

Bart:
Why don't you just try it.
See what happens if an exception occurs in TryThisFunction, and what happens if it does not.

You learn more from experimenting than from me just telling you.

Bart

zeljko:

--- Quote from: dieselnutjob on April 01, 2014, 06:43:30 pm ---Comparing these to codes


--- Code: ---try
  trythisfunction;
finally
  alwaysdothisfunction;
end;

--- End code ---


--- Code: ---try
  trythisfunction;
finally
  ;
end;
alwaysdothisfunction;

--- End code ---

Don't they do exactly the same thing?

--- End quote ---

If your example works ok then it will look same, but it isn't same.
try this:

procedure TestTryFinally;
begin
   try
      exit;
   finally
      writeln('I''m in finally block !');
   end;
   writeln('I will not come here.');
end;

That means: In any case, code in finally block is excuted. In your example if yours trythisfunction; crashes or exits
alwaysdothisfunction() will never execute since it is out of finally block.


dieselnutjob:
ok I think I get it.

my understanding:-

if anything in the "try" section causes an exception or crashes then the code in "finally" is guaranteed to still take place, but after that the program will still be crashed or excepted as the guarantee is finished.

This explains why exception handling code is in the "finally" section because it is guaranteed to run, thereby clearing down the exception so that the rest of the code can then still work.

Is that right?

Looking at this example

--- Code: ---// Previous code
  MySection.Acquire;
  Try
    // Protected code
  Finally
    MySection.Release;
  end;
  // Other code.

--- End code ---

from http://www.freepascal.org/docs-html/fcl/syncobjs/tcriticalsection.html

why do they suggest the "Try" and "Protected code"?
is it because if that Protected code crashed then the MySection would be locked forever and other threads would never be able to get in?

does that mean that if the "Protected code" is actually really well written and therefore will never crash that the whole Try Finally End thing isn't really necessary?

BigChimp:
Yes and yes ;)

... I think the point here is that the protected code can also call other code that may not be reliable or code that depends on something (e.g. a db/network connection that may be unreliable)

Navigation

[0] Message Index

[#] Next page

Go to full version