Solved

try and finally

Posted on 2001-06-11
7
159 Views
Last Modified: 2010-04-06
what is the importance of this instruction try and finally
please give an example in which this instructions are best suited for...
0
Comment
Question by:aerokevs
7 Comments
 
LVL 22

Accepted Solution

by:
Mohammed Nasman earned 10 total points
ID: 6176259
Hello

  if you want to execute some code, like create a button in run time, and u want to free that after u finish the operation if the code worked fine or you if got error the try clause will execute the finally part, you can find more info in the help.

from delphi help:

Try...finally statements

Sometimes you want to ensure that specific parts of an operation are completed, whether or not the operation is interrupted by an exception. For example, when a routine acquires control of a resource, it is often important that the resource be released, regardless of whether the routine terminates normally. In these situations, you can use a try...finally statement.
The following example shows how code that opens and processes a file can ensure that the file is ultimately closed, even if an error occurs during execution.

Reset(F);

try
 ...  // process file F
finally
  CloseFile(F);
end;

The syntax of a try...finally statement is

try statementList1 finally statementList2 end

where each statementList is a sequence of statements delimited by semicolons. The try...finally statement executes the statements in statementList1 (the try clause). If statementList1 finishes without raising exceptions, statementList2 (the finally clause) is executed. If an exception is raised during execution of statementList1, control is transferred to statementList2; once statementList2 finishes executing, the exception is re-raised. If a call to the Exit, Break, or Continue procedure causes control to leave statementList1, statementList2 is automatically executed. Thus the finally clause is always executed, regardless of how the try clause terminates.

If an exception is raised but not handled in the finally clause, that exception is propagated out of the try...finally statement, and any exception already raised in the try clause is lost. The finally clause should therefore handle all locally raised exceptions, so as not to disturb propagation of other exceptions.


0
 

Expert Comment

by:mike_tipping
ID: 6176981
Or in other words...

If you wrap a:

Try
  ...
Finally
  ...
end; //finally

Around something, the thing you put in the fially will be executed no matter what happens between the try and the finally. As Mnasman says, an obviouse example of this is if you create a memory object so:

myTList := Tlist.Create;
Try
  //Do somthign with  myTList
Finally
  if Assigned(myTList) then
    myTList.Free;
end; //Finally

So the myTlist is always free'd even if the code crashes during the 'Do somthign with  myTList' bit.

   
0
 
LVL 8

Expert Comment

by:TOndrej
ID: 6178082
Hi mike_tipping,

myTList := TList.Create;
try
 //Do somthign with  myTList
finally
  if Assigned(myTList) then // this is unnecessary - Free checks for nil
    myTList.Free; // besides, myTList can never be nil here,
    // unless it's assigned value of nil somewhere in "Do somthign" part
end;
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 27

Expert Comment

by:kretzschmar
ID: 6180282
try
  to get an answer
finally
  grade the expert
end;

:-))
0
 
LVL 4

Expert Comment

by:StevenB
ID: 6184120
 ... of course really safe coders do something like this ...

myTList := TList.Create;
try
  //Do somthign with myTList
finally
  myTList.Free;
  myTList := Nil;
end;

  ... or better still ...

myTList := TList.Create;
try
  //Do somthign with myTList
finally
  FreeAndNil(myTList);
end;

  This ensures that you don't inadvertently access violate when you accidentally try and access myTList after it's been freed.



  aerokevs, the message is that you should use try .. finally EVERY time you create an object at run time which needs cleaning up, always protect your resources like this. If you have multiple objects it's safest to do something like this:


Object1 := TObject1.Create;
try
  Object2 := TObject2.Create;
  try
    // Do something with your objects
  finally
    FreeAndNil(Object2);
  end;
finally
  FreeAndNil(Object1);
end;

  The alternative:

Object1 := TObject1.Create;
Object2 := TObject2.Create;
try
  // Do something with your objects
finally
  FreeAndNil(Object2);
  FreeAndNil(Object1);
end;

  could potentially lead to problems if there is an exception raised during either
Object2 := TObject2.Create;
or
FreeAndNil(Object2);

  the lesson is to start the try block immediately after the create and to free the object immediately after the finally statement.
 
0
 

Author Comment

by:aerokevs
ID: 6189695
can try and finally be useful in databases too..
0
 
LVL 4

Expert Comment

by:StevenB
ID: 6189720
 It can be useful anywhere you want to ensure that a certain piece of code is executed, whether an exception is thrown or not. In the case of databases it would be good practice to use it to ensure that your queries and tables are closed, to prevent your application locking out a table.
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A lot of questions regard threads in Delphi.   One of the more specific questions is how to show progress of the thread.   Updating a progressbar from inside a thread is a mistake. A solution to this would be to send a synchronized message to the…
Introduction I have seen many questions in this Delphi topic area where queries in threads are needed or suggested. I know bumped into a similar need. This article will address some of the concepts when dealing with a multithreaded delphi database…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question