Delphi中的C#/ Java“Try/Finally/Catch”等效构造

前端之家收集整理的这篇文章主要介绍了Delphi中的C#/ Java“Try/Finally/Catch”等效构造前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Delphi中,你怎么用try,finally,catch?一个Java / C#等效的东西看起来像:
  1. try {
  2. // Open DB connection,start transaction
  3. } catch (Exception e) {
  4. // Roll back DB transaction
  5. } finally {
  6. // Close DB connection,commit transaction
  7. }

如果你在Delphi中尝试这个,你可以使用try / finally或try / except;但从来没有三个在一起。我想要的代码如下(不编译):

  1. try
  2. // Open DB connection,start transaction
  3. except on e: Exception do
  4. begin
  5. // Roll back transaction
  6. end
  7. finally // Compiler error: expected "END" not "finally"
  8. begin
  9. // Commit transaction
  10. end

解决方法

在Delphi中,您可以使用以下模式:
  1. // initialize / allocate resource (create objects etc.)
  2. ...
  3. try
  4. try
  5. // use resource
  6. ...
  7. except
  8. // handle exception
  9. ...
  10. end;
  11. finally
  12. // free resource / cleanup
  13. ...
  14. end

猜你在找的Delphi相关文章