PDA

View Full Version : try - finally!



Sir R. M8gic1an
05-09-2008, 11:04 AM
i really think this is better fit in SRL Library, but since the other thread got moved here >.>

anyway, yesterday i need to make sure my bitmaps we're freed at the end of a function. I had seen wizzup? using the finally command before but i didn't remember too well how he had done it.

so i went into srl chat and asked if anyone knew how to use it. bullzeye was there and gave me an example with try except and finally. finally would run independently from try finding a runtime error or not. in his opinion finally was pretty much useless. i played around with it for a bit.


program New;

Procedure WriteThis;
begin
try wait(1);
writeln('some here 1');
writeln('some here 2');
exit;
writeln('some here 3');
writeln('some here 4');
finally
writeln('Using the Finally command!');
end;
end;

begin
WriteThis;
end.




Successfully compiled (222 ms)
some here 1
some here 2
Using the Finally command!
Successfully executed


he was happy to find a new way to use finally.

by putting try wait(1); you lose only 1 or 2 ms and you get to call the finally command. i used it to ensure i'd free the bitmaps. notice that although i called exit; it still did what was after finally.

~RM

Kave
05-09-2008, 11:07 AM
So what finally does is that no matter what, anything after finally is executed? If so that could be useful for Freeing items, or extra debug information maybe.

Sir R. M8gic1an
05-09-2008, 11:10 AM
exactly kave :) but don't forget that you need to call try first. it will give an error if you call finally but not try.

~RM

Timothegreat
05-16-2008, 02:32 AM
really useful, might try using it in my upcoming scripts

Markus
05-16-2008, 12:52 PM
Exactly what I posted some time back:

Suggestion: a try .. finally block :)
They aren't used that much (actually, I never saw them used to their full potentional), but are EXTREMELY useful for avoiding memory leaks:


program TryFinallyDemo;
procedure ThisIsNowANonLeakingProcedure;
begin
try
writeln('Here I load a Bitmap/DTM');
exit; //SOme condition here
writeln('And here I often get a leak');
finally
writeln('But with Try ... Finally, I won''t leak, wewt :)');
end;
end;
begin
ThisIsNowANonLeakingProcedure;
end.


See? Instead of

if randomcraphere then
begin
FreeBitmap(SomeBitmap);
exit;
end;
FreeBitmap(SomeBitmap);

We can just do:


try
if RandomCrap then
exit;
finally
FreeBitmap(SomeBitmap);
end;


Result: code is clean, no leak, no more messing around and it owns :)

R0b0t1
05-16-2008, 10:28 PM
I normally use it while init'ing Bitmaps...

Nava2
05-22-2008, 12:15 AM
Would work for DTM's too :) Might look into using this.

Nava2

the scar noob
05-22-2008, 09:25 AM
Would work for DTM's too :) Might look into using this.

Nava2

Indeed, use finally to free the DTM then;)

-Tsn.