在delphi 7中,是`try ...除了raise; 结束;"有意义吗?

Blo*_*ard 7 delphi exception try-catch delphi-7

在我维护的一些Delphi 7代码中,我注意到以下很多实例:

with ADOQuery1 do begin
  // .. fill out sql.text, etc
  try
    execSQL;
  except
    raise;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

在我看来,这些尝试块可以被删除,因为它们什么都不做.但是,我对可能出现的微妙副作用持谨慎态度.

任何人都可以想到这些块实际上可以做任何没有它们的情况下会发生的事情吗?

Mik*_*keJ 10

在这种情况下,raise操作没有任何效果,应该删除它,因为它只是重新引发异常块刚刚捕获的异常.raise通常用于在没有适当的错误处理时将控制转移到块的末尾.在下面我们处理自定义异常,但任何其他异常应该在别处处理.

try
  someOperation;
except
  on e: ECustomException do
    SomeCustomHandelr;
  else
     begin
       // the raise is only useful to rethrow the exception to an encompasing 
       // handler.  In this case after I have called my logger code. as Rob
       // mentioned this can be omitted if you arent handling anything because
       // the compiler will simply jump you to the next block if there is no
       // else.
       LogUnexpectedException('some operation failed',e);
       raise;
     end;
end;
Run Code Online (Sandbox Code Playgroud)

小心有没有"提高"的类似外观形式,它具有吃/隐藏任何例外的副作用.非常肆无忌惮的开发人员的实践,他们希望能够在竞争中占据一席之地.

with ADOQuery1 do begin  
  // .. fill out sql.text, etc  
  try    
    execSQL; 
  except
    // no handler so this just eats any "errors"    
  end;
Run Code Online (Sandbox Code Playgroud)

  • 迈克,你的第一个例子不需要"加注".任何非ECustomException类型的异常都会自动传播到下一个处理程序.只需省略整个"其他"部分即可. (2认同)

Hem*_*ant 6

删除上面代码段中的except代码将没有任何区别.您可以(我相信您应该因为它降低了可读性)将其删除.