C#/Java“Try/Finally/Catch"Delphi 中的等效结构

C#/Java“Try/Finally/Catch

问题描述:

在 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