尝试/除外/最后订单

时间:2014-07-09 04:47:03

标签: exception-handling delphi

高代表用户another question发表评论我今天早些时候曾问过,最好换掉try / finally和try / except的顺序。

所以,而不是:

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;

它将try / finally嵌套在里面,try / except在外面:

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;

我想知道何时使用这个成语是合适的,也是个好主意,是否有特殊情况你不应该这样做?为什么选择一个而不是另一个?我认为清理代码中抛出的异常将是主要的考虑因素,因为我认为它可以抑制其中一个例外,如果最终抛出异常,但可以防止意外冒泡错误?

1 个答案:

答案 0 :(得分:5)

你可以同时使用try,catch和finally的写法,因情况而异。

考虑以下代码清单,以便尝试...除了在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;

上面的代码清单显示了try ...的用法,除了在try ... finally块中。

考虑下面的代码列表,试试看...最后在try ...中除外。

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;

这里上面的代码清单可以用于这样的情况,其中函数仅返回true和false。如果发生了一些异常,则只需将该值设置为false。