在我维护的一些Delphi 7代码中,我注意到以下很多实例:
在我看来,这些尝试块可以被删除,因为它们什么都不做.但是,我对可能出现的微妙副作用持谨慎态度.
任何人都可以想到这些块实际上可以做任何没有它们的情况下会发生的事情吗?
解决方法
在这种情况下,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;
小心有没有“加注”的类似外观形式,它具有吃/隐藏任何例外的副作用.非常肆无忌惮的开发人员的实践,他们希望能够在竞争中占据一席之地.