C#/Java“Try/Finally/Catch"Delphi 中的等效结构 [英] C#/Java "Try/Finally/Catch" equivalent construct in Delphi

查看:31
本文介绍了C#/Java“Try/Finally/Catch"Delphi 中的等效结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Delphi 中,如何使用 try、finally 和 catch?Java/C# 等价物看起来像:

In Delp how can you use try, finally, and catch together? A Java/C# equivalent would look something like:

try {
    // Open DB connection, start transaction
} catch (Exception e) {
    // Roll back DB transaction
} finally {
    // Close DB connection, commit transaction
}

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

If you try this in Delp you can either use try/finally or try/except; but never all three together. I would like code like the following (which doesn't compile):

try
    // Open DB connection, start transaction
except on e: Exception do
begin
    // Roll back transaction
end
finally // Compiler error: expected "END" not "finally"
begin
    // Commit transaction
end

推荐答案

在 Delphi 中你可以使用以下模式:

In Delphi you can use the following pattern:

// initialize / allocate resource (create objects etc.)
...
try
  try
    // use resource
    ...
  except
    // handle exception
    ...
  end;
finally
  // free resource / cleanup
  ...
end

这篇关于C#/Java“Try/Finally/Catch"Delphi 中的等效结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆