Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#/Java "Try/Finally/Catch" equivalent construct in Delphi

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
like image 878
ashes999 Avatar asked Nov 11 '10 15:11

ashes999


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C full form?

Originally Answered: What is the full form of C ? C - Compiler . C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.


2 Answers

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
like image 90
mjn Avatar answered Nov 09 '22 06:11

mjn


write

try 
  // allocate resource here
  try 
  finally
    // free resource here
  end;
except
  // handle exception here
end;
like image 21
Eugene Mayevski 'Callback Avatar answered Nov 09 '22 05:11

Eugene Mayevski 'Callback