Solved

try and finally

Posted on 2001-06-11
7
157 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:
mnasman 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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Objective: - This article will help user in how to convert their numeric value become words. How to use 1. You can copy this code in your Unit as function 2. than you can perform your function by type this code The Code   (CODE) The Im…
Introduction Raise your hands if you were as upset with FireMonkey as I was when I discovered that there was no TListview.  I use TListView in almost all of my applications I've written, and I was not going to compromise by resorting to TStringGrid…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

705 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now