Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

transaction : except or on e:exception?

Tags:

delphi

What exactly is the difference (and what to use) between :

try
  UniTransaction1.Commit;
except
  UniTransaction1.Rollback;
end;

and :

try
  UniTransaction1.Commit;
except
  on E:exception do
    UniTransaction1.Rollback;
end;

Is not 'except' an exception already ?

like image 382
user3351050 Avatar asked Dec 18 '16 08:12

user3351050


1 Answers

The former will catch all objects raised as exceptions, the latter only those that derive from the class Exception.

It is not very well known but Delphi does cater for raising exceptions that do not derive from Exception. That is you are perfectly at liberty to raise an exception with an object that does not derive from Exception. In practise, I have never encountered such things. You simply don't ever see code that raises anything that does not derive from Exception. To all intents and purpose this means that the two variants will behave identically.

Since you do not refer to the exception object, there seems little need for you to declare a variable which you never use. Which brings us to yet another option:

on Exception do
  .... 

This will catch all the same exceptions as your second variant, but does not declare a variable which can reference the exception object.

Which one should you use? You can use any of them and have the same behaviour, assuming of course that you don't encounter exceptions that do not derive from Exception. Were it me I would opt for your first option. It is the most concise, and it simply says that you wish this code to happen in case of any exception.

like image 139
David Heffernan Avatar answered Oct 10 '22 01:10

David Heffernan