Jessica Brown
Jessica Brown

Reputation: 8312

Try/Except/Finally Order

A comment by a high rep user on another question I asked earlier today suggested it would be better to swap the order of try/finally and try/except.

So, instead of this:

try
  try
    //some code
    //something that throws an exception, eg: EIndexOutOfRangeException 
    //more code
  except on E : EIndexOutOfRangeException do begin .... end;
finally
  // some cleanup code
end;

it would have the try/finally nested inside and the try/except on the outside:

try
  try
    //some code
    //something that throws an exception, eg: EIndexOutOfRangeException 
    //more code
  finally
    // some cleanup code
  end;
except on E : EIndexOutOfRangeException do begin .... end;
end;

I would like to know when is it appropriate and a good idea to use this idiom, and are there exceptional cases where you shouldn't? Why prefer one over the other? I suppose exceptions being thrown in the cleanup code would be the main consideration, since I imagine it could suppress one of the exceptions if finally throws an exception, but could prevent unexpected bubbling up of errors?

Upvotes: 3

Views: 4025

Answers (1)

Rahul Sharma
Rahul Sharma

Reputation: 347

You can use both the ways of writing try,catch and finally and it varies from situation to situation.

Consider the following code listing for try...except inside try...finally.

//You will receive a DataSet is some state.
try   
   try
      //Here you'll change its state and perform operations on it.
      //If some exception occurred you will handle it.
   except
      //Handle exception.
   end;  
finally
 //Put the DataSet again in the same state.
end;

The above code listing shows the uses of try...except inside a try...finally block.

Consider the following code listing for try...finally inside try...except.

try  
   LObject:= TObject.Create;
   //Create an Object. It better idea to create an object outside try..finally block.
   //If some exception occured while creating an object an exception will be thrown.
   //However its not a good idea to catch such an exception.Let the system handle it.
   try
      //Use the Object. 
   finally
      //Free Object.
   end;  
  // Returns True
except
  // Returns False.
end;

Here the above code listing may be used in such a situation where the function return only true and false. If some exception occurred then simply set the value to false.

Upvotes: 6

Related Questions