【问题标题】:Try/Except/Finally Order尝试/排除/最终订购
【发布时间】:2014-07-09 04:47:03
【问题描述】:

我今天早些时候问过的一位高级用户在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;

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

【问题讨论】:

  • 这完全取决于您作为 cmets 提供的代码。

标签: exception-handling delphi


【解决方案1】:

try、catch 和 finally 这两种写法都可以使用,具体情况因情况而异。

考虑下面的 try...except 内部代码清单 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...except 在 try...finally 块中的用法。

考虑下面的 try...finally 代码清单,里面是 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;

这里上面的代码清单可以用在函数只返回真假的情况下。如果发生异常,只需将值设置为 false。

【讨论】:

  • 第二个例子中的注释是Let the system handle it. 但是为什么在try .. except then 中吞没了异常?
  • 我想说的是,如果在创建对象时发生了一些异常,假设在这种情况下没有足够的内存分配给该对象,我们应该让系统处理它,但是这种情况非常罕见。如果我在某个地方错了,请赐教。
  • 我相信@mjn 所指的令人困惑的一点是您的评论说“让系统处理它”但后面的代码不允许系统处理它,因为你有一个 except 块,可以捕获TObject.Create 抛出的任何东西。
  • @Andriy 完全正确,代码按照评论所说的那样做,所以其中一个肯定是错误的
  • 我将评论和代码读作“处理感兴趣的异常,引发所有其他异常”。无条件吞下所有异常是不常见的,不是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-29
  • 2021-05-17
  • 1970-01-01
相关资源
最近更新 更多