在Delphi中,你怎么用try,finally,catch?一个Java / C#等效的东西看起来像:
- try {
- // Open DB connection,start transaction
- } catch (Exception e) {
- // Roll back DB transaction
- } finally {
- // Close DB connection,commit transaction
- }
如果你在Delphi中尝试这个,你可以使用try / finally或try / except;但从来没有三个在一起。我想要的代码如下(不编译):
- 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中,您可以使用以下模式:
- // initialize / allocate resource (create objects etc.)
- ...
- try
- try
- // use resource
- ...
- except
- // handle exception
- ...
- end;
- finally
- // free resource / cleanup
- ...
- end