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

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

问题描述

在德尔福,你怎么可以用try,finally,catch一起?一个Java / C#等效的东西看起来像:

  try {
//打开数据库连接,启动事务
} catch(Exception e){
//回滚DB事务
} finally {
//关闭DB连接,提交事务
}

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

  try 
//打开数据库连接,启动事务
除了e:异常do
begin
//回滚事务
end
finally //编译器错误:预期的END不是finally
begin
//提交事务
end


解决方案

在Delphi中,您可以使用以下模式:

  //初始化/分配资源(创建对象等) )
...
尝试
尝试
//使用资源
...
除了
//处理异常
...
end;
finally
// free resource / cleanup
...
end


In Delphi, 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
}

If you try this in Delphi, 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

解决方案

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天全站免登陆