SRL Archive - OSR Outdated Tutorials

try - finally!


Sir R. M8gic1an

2008-05-09 07:04:42

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

2008-05-09 07:07:43

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

2008-05-09 07:10:18

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

2008-05-15 22:32:30

really useful, might try using it in my upcoming scripts

Markus

2008-05-16 08:52:05

Exactly what I posted some time back:
From: Markus
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

2008-05-16 18:28:18

I normally use it while init'ing Bitmaps…

Nava2

2008-05-21 20:15:53

Would work for DTM's too :) Might look into using this.

Nava2

the scar noob

2008-05-22 05:25:06

From: Nava2
Would work for DTM's too :) Might look into using this.

Nava2


Indeed, use finally to free the DTM then;)

-Tsn.