简体   繁体   English

尝试/除外/最后订单

[英]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. 高代表用户对我今天早些时候提出的另一个问题的评论表明,更换try / finally和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 / 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;

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? 我认为清理代码中抛出的异常将是主要的考虑因素,因为我认为它可以抑制其中一个例外,如果最终抛出异常,但可以防止意外冒泡错误?

You can use both the ways of writing try,catch and finally and it varies from situation to situation. 你可以同时使用try,catch和finally的写法,因情况而异。

Consider the following code listing for try...except inside try...finally. 考虑下面的代码清单try ...除了在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. 上面的代码清单显示了try ...的用法,除了在try ... finally块之外。

Consider the following code listing for try...finally inside try...except. 考虑以下代码清单,尝试尝试...最后在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;

Here the above code listing may be used in such a situation where the function return only true and false. 这里,上述代码清单可以用于这样的情况,其中函数仅返回true和false。 If some exception occurred then simply set the value to false. 如果发生了一些异常,则只需将该值设置为false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM