Recent

Author Topic: What is good in using try..finally?  (Read 21942 times)

alpine

  • Hero Member
  • *****
  • Posts: 1064
Re: What is good in using try..finally?
« Reply #75 on: October 09, 2021, 04:14:01 pm »
Then the 440bx standpoint that is actually revealed quite late into the discussion - exception handling is bad, because it is the only way to return error when assigning to a property, which is part of the Pascal implementation of OOP. Because of that developer is forced to use it, and that is presumably a bad thing.
I'm not sure why you say "quite late" given that I stated my view on the matter in my very first post in this thread.
As late as of reply #46. There is your first mentioning of "properties".

@440bx,
That is the way I'm getting it, correct me if I'm wrong.
Exceptions are great when a program has to deal with unpredictable behavior such as accessing some resource that is _not_ under its control.  That's what exceptions are for.  Using exceptions to simply inform the caller that something unexpected happened is a gross misuse of exceptions.  A prime example is their use in setters to inform the caller an error or unexpected condition took place.
Why you consider that wrong?
"I'm sorry Dave, I'm afraid I can't do that."
—HAL 9000

kupferstecher

  • Hero Member
  • *****
  • Posts: 583
Re: What is good in using try..finally?
« Reply #76 on: October 09, 2021, 05:57:09 pm »
*snip*
As per statistics finally is 70X more used than except. Still to me try..except is the more natural use (just like in C++ there is only try..catch).
The prevalence of the finally is because it is a common practice to do this:
Code: Pascal  [Select][+][-]
  1.   L := TStringList.Create;
  2.   try
  3.     // use L
  4.   finally
  5.     L.Free;
  6.   end;


In my understanding try..finally doesn't really handle an exception, as it re-raises it directly after executing the finally block. An unhandled exception stops the application, which would render the above code useless. But in a GUI-application there is the LCL above handling the exception. One could see it as a nested try block, always with the LCLs try..except in the very top. And because it is there, it's not needed in the levels below. I see it as a concept, that an exception should bring the program flow immediately back to the application loop, and thats where the LCLs try..except is located. The "immediately" is only delayed by the finally-blocks in deeper code levels that clean up the mess that the exception caused.

application.inc:
Code: Pascal  [Select][+][-]
  1. {------------------------------------------------------------------------------
  2.   TApplication RunLoop
  3.   control is passed to event processor.
  4. ------------------------------------------------------------------------------}
  5. procedure TApplication.RunLoop;
  6. begin
  7.   repeat
  8.     if CaptureExceptions then
  9.       try // run with try..except
  10.         HandleMessage;
  11.       except
  12.         HandleException(Self);
  13.       end
  14.     else
  15.       HandleMessage; // run without try..except
  16.   until Terminated;
  17. end;    

« Last Edit: October 09, 2021, 05:59:23 pm by kupferstecher »

440bx

  • Hero Member
  • *****
  • Posts: 4030
Re: What is good in using try..finally?
« Reply #77 on: October 09, 2021, 06:10:03 pm »
As late as of reply #46. There is your first mentioning of "properties".
I mentioned the problem in my very first post.  I mentioned properties as an example of a construct that causes the problem in post #46.


Why you consider that wrong?
because cross stack frame gotos should not be used to handle run of the mill errors.  Cross stack frame gotos (exceptions) can cause a myriad of problems, they should be used when they are the only way to handle an error (for instance, access violations caused by an attempt to read memory that isn't managed by the program)
(FPC v3.0.4 and Lazarus 1.8.2) or (FPC v3.2.2 and Lazarus v3.2) on Windows 7 SP1 64bit.

MarkMLl

  • Hero Member
  • *****
  • Posts: 6686
Re: What is good in using try..finally?
« Reply #78 on: October 09, 2021, 08:18:44 pm »
because cross stack frame gotos should not be used to handle run of the mill errors.  Cross stack frame gotos (exceptions) can cause a myriad of problems, they should be used when they are the only way to handle an error (for instance, access violations caused by an attempt to read memory that isn't managed by the program)

As you pointed out in your #9... agreed, and the cross-frame issue is also one I tried to mention when I first posted in this thread (#35): it's what distinguishes exceptions from try/finally. And the problems are specifically what Warfley found himself wrestling with when he was working on coroutines a few weeks ago.

I'd cautiously agree with your position in #9 that a program never actually /needs/ try/finally, but it's useful syntactic sugar. And given the introduction of that bit of syntactic sugar, I think it's arguably unfortunate that the Object Pascal designers didn't introduce something comparable to accommodate "nearby" failures such as predictable albeit uncommon errors in property getters or setters. But I really don't like the bad argument that condemns OOP because of this one specific problem in the way that people tend to use this one specific language implementation.

MarkMLl


MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

Martin_fr

  • Administrator
  • Hero Member
  • *
  • Posts: 9870
  • Debugger - SynEdit - and more
    • wiki
Re: What is good in using try..finally?
« Reply #79 on: October 09, 2021, 09:06:44 pm »
As late as of reply #46. There is your first mentioning of "properties".
I mentioned the problem in my very first post.  I mentioned properties as an example of a construct that causes the problem in post #46.
Quote
Unfortunately, the Pascal implementation of OOP often forces the use of "try-except" because it's the only way to let the caller of some code know that a problem occurred.  Lastly, keep in mind that a "try-except" is nothing more than a cross stack frame goto  mechanism which is the worst kind of goto there is.

1) The "Pascal implementation" of non OOP, also forces the user. (e.g. StrToInt)

2) I am assuming that in the quoted text "Pascal implementation" refers to the rtl/fcl/lcl/...
Neither OOP itself, nor the way the fpc compiler handles it, introduce any such force.
Neither OOP itself, nor the way the fpc compiler handles it, demand that code that can return an error must go into a property.
Such code can (within OOP) be written in other ways, that can return the error as result (or out param, or via a LastError call). All at the choice of the author of any code (including frameworks).

Yet, if "Pascal implementation" refers to the rtl/fcl/lcl/ then yes, the rtl/fcl/lcl introduce such "possibility" (see below, not always a "force") by introducing classes that contain properties that raise exceptions. But also introducing functions (non-oop)

Sure StrToInt is easier to replace than e.g. TList. But then
- StrToInt is just one example
- Without oop, instead of TList you use arrays (or similar constructs). For those you need to check bounds in advance. For TList you can check bounds in advance too, avoiding the need of "try except" blocks, as you ensure no exception will be risen. So in this case the rtl/fcl/lcl still do NOT (always or "often") force the user to use "try except"

Some classes may not offer advanced checks to avoid exceptions. But then, neither does StrToInt.
The user can then chose not to use those classes at all (same as StrToInt).

I think the example (quoted above) is poorly worded:
1) "Pascal implementation of OOP" should make it clear that it is about the frameworks. And then once that is clear, it is the entire framework, including non-oop parts.
2) "often forces" well actually no: not forces, merely offers. In many cases alternative options are given. But sometimes, maybe yes: Some parts of the framework forces the use of exceptions, IF the user wants to use that part of the framework. (but again OOP and non-OOP).

alpine

  • Hero Member
  • *****
  • Posts: 1064
Re: What is good in using try..finally?
« Reply #80 on: October 09, 2021, 09:12:39 pm »
As late as of reply #46. There is your first mentioning of "properties".
I mentioned the problem in my very first post.  I mentioned properties as an example of a construct that causes the problem in post #46.

Turning back to your first post (reply #9):
My though would be that either I can handle the exception in except and then I do not need finally, code is OK without it; OR I do not know what went wrong (an exception I cannot handle), but then it might be too risky to continue with any code after that even in finally. Now I see the benefit of catching some exceptions, but re-raising some others and still do some final activity. This would however make the language improvement request seen elsewhere to allow try..except..finally..end in one block a lot of sense, so one would not need two nested try-s.
I'm going to give you a piece of advice that is quite likely many OOP programmers will disagree with, which is, a bug-free program never needs a "try-finally" and extremely rarely needs a "try-except".  "try-finally" should never be used and the only times "try-except" may be acceptable is when writing a program that deals with resources that are not under its control. 
Here I can see recommendations, not problems.

IOW, the presence of a "try-finally" is a clear indicator that the code has logical flow deficiencies and, the presence of a "try-except" is almost always an indicator of the same.
Unsubstantiated statements.

Unfortunately, the Pascal implementation of OOP often forces the use of "try-except" because it's the only way to let the caller of some code know that a problem occurred.
Here all readers should guess that you're actually talking about properties.

Lastly, keep in mind that a "try-except" is nothing more than a cross stack frame goto  mechanism which is the worst kind of goto there is.
It is actually more that a goto, it is a language construct with it's defined semantics. Otherwise, we can say for every control structure: it is nothing more than a goto. What about the threads? Aren't they worst than "try-except"?

Why you consider that wrong?
because cross stack frame gotos should not be used to handle run of the mill errors.  Cross stack frame gotos (exceptions) can cause a myriad of problems, they should be used when they are the only way to handle an error (for instance, access violations caused by an attempt to read memory that isn't managed by the program)
Isn't it error to try accessing e.g. TStrings.Items[ I ] with I beyond the current size of the collection?

What kind (myraid) of problems can cause the use of "try-except"? Please specify.

*snip*
As you pointed out in your #9... agreed, and the cross-frame issue is also one I tried to mention when I first posted in this thread (#35): it's what distinguishes exceptions from try/finally. And the problems are specifically what Warfley found himself wrestling with when he was working on coroutines a few weeks ago.
I agree that the implementation of such features could be treacherous. But we're discussing their usage, not implementation.
"I'm sorry Dave, I'm afraid I can't do that."
—HAL 9000

MarkMLl

  • Hero Member
  • *****
  • Posts: 6686
Re: What is good in using try..finally?
« Reply #81 on: October 09, 2021, 09:24:14 pm »
Neither OOP itself, nor the way the fpc compiler handles it, introduce any such force.
Neither OOP itself, nor the way the fpc compiler handles it, demand that code that can return an error must go into a property.
Such code can (within OOP) be written in other ways, that can return the error as result (or out param, or via a LastError call). All at the choice of the author of any code (including frameworks).

Yet, if "Pascal implementation" refers to the rtl/fcl/lcl/ then yes, the rtl/fcl/lcl introduce such "possibility" (see below, not always a "force") by introducing classes that contain properties that raise exceptions. But also introducing functions (non-oop)

I rarely use emoticons. I never use animated emoticons, and look down on people who do.

But it's getting to the point where it's unfortunate that this particular instance of SMF hasn't enabled :horse: :-)

Somewhat later. As a couple of historical points:

* By the late 1960s, the Burroughs ALGOL compiler allowed a procedure to be associated with an exceptional condition such as a divide by zero, but this was more like an interrupt handler than part of the normal block structure.

* The Wp article https://en.wikipedia.org/wiki/Mesa_(programming_language)#Syntax refers to Xerox PARC hiring an unidentified graduate from Colorado who defined their exception handling semantics, but elsewhere Jim Mitchell (https://en.wikipedia.org/wiki/James_G._Mitchell) is credited with doing the work there.

MarkMLl

« Last Edit: October 09, 2021, 10:25:02 pm by MarkMLl »
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

440bx

  • Hero Member
  • *****
  • Posts: 4030
Re: What is good in using try..finally?
« Reply #82 on: October 09, 2021, 11:11:38 pm »
But I really don't like the bad argument that condemns OOP because of this one specific problem in the way that people tend to use this one specific language implementation.
I don't condemn OOP just because of that.  That's just one (1) of the many reasons I strongly dislike OOP.  The reason I'm elaborating on exceptions is because it's closely related to the initial topic of the thread.




1) The "Pascal implementation" of non OOP, also forces the user. (e.g. StrToInt)
Yes, that is true but, it would be very easy to provide an implementation of StrToInt that didn't raise an exception in case of a conversion error.  The same cannot be said about setters.

2) I am assuming that in the quoted text "Pascal implementation" refers to the rtl/fcl/lcl/...
Actually, it refers to how the OOP portion is designed and implemented.  That would include the RTL but, the implementation of the LCL (for instance) is, to a significant extent, a result of how OOP is implemented in Pascal.

Neither OOP itself, nor the way the fpc compiler handles it, introduce any such force.
That statement is valid only if properties are not considered part of OOP, which is something some participants in this thread claim.  A claim that I consider "unconvincing".

Neither OOP itself, nor the way the fpc compiler handles it, demand that code that can return an error must go into a property.
Maybe so but, when a programmer uses properties and encounters an error condition in a setter, there doesn't seem to be any alternatives to raising an exception.

Such code can (within OOP) be written in other ways, that can return the error as result (or out param, or via a LastError call). All at the choice of the author of any code (including frameworks).
I can see that but, then it wouldn't be a property anymore.  What I'm saying here is, the language provides properties, programmers use them because they are available and, as a result they have to use exceptions.  IOW, I don't see Pascal programmers making any efforts to avoid setters and the consequent need for exceptions.


- Without oop, instead of TList you use arrays (or similar constructs). For those you need to check bounds in advance. For TList you can check bounds in advance too, avoiding the need of "try except" blocks, as you ensure no exception will be risen. So in this case the rtl/fcl/lcl still do NOT (always or "often") force the user to use "try except"
From the point of view of what can be done, what you've presented is very reasonable but,  from what I've seen, OOP programmers would rather enclose their code in a "try-except" than do any pre-condition checking.

Some classes may not offer advanced checks to avoid exceptions. But then, neither does StrToInt.
The user can then chose not to use those classes at all (same as StrToInt).
It seems to me that the better solution would be to have implementations don't depend on exceptions to return errors.

2) "often forces" well actually no: not forces, merely offers. In many cases alternative options are given. But sometimes, maybe yes: Some parts of the framework forces the use of exceptions, IF the user wants to use that part of the framework. (but again OOP and non-OOP).
What good is it to have a framework if some of it has to be avoided ?



Here all readers should guess that you're actually talking about properties.
I'm definitely guilty of expecting the readers to know Object Pascal and be aware of properties among other things.  I guess my expectations are misplaced.

Isn't it error to try accessing e.g. TStrings.Items[ I ] with I beyond the current size of the collection?
I've never used TStrings, I'm going to guess that it is an error.  Are you using that as an example to justify the use of exceptions ?

What kind (myraid) of problems can cause the use of "try-except"? Please specify.
Yes, there are really a myriad but, one of them is already enough to use them only when strictly necessary and that is, it is a cross stack frame goto.  A goto that does not cross stack frames is already undesirable, one that crosses stack frames is orders of magnitud more undesirable and, you should know why. 
(FPC v3.0.4 and Lazarus 1.8.2) or (FPC v3.2.2 and Lazarus v3.2) on Windows 7 SP1 64bit.

Martin_fr

  • Administrator
  • Hero Member
  • *
  • Posts: 9870
  • Debugger - SynEdit - and more
    • wiki
Re: What is good in using try..finally?
« Reply #83 on: October 10, 2021, 12:14:49 am »
You imply (falsely) that properties must be used for everything.
There are existing properties, that do not (never) throw exceptions. Those are examples where properties cause no problem (in relation to a discussion on exceptions).

Code that need exceptions, well it can be implemented as a method, a "function of object" that can return the error. The option of having properties is not a mandate to use nothing else but properties.

The existence of code throwing exceptions (including in properties) is not mandated by OOP, nor by the compiler, nor by the existence of properties. It is a choice.
Only due to the use in the framework, the choice becomes limited. (for both OOP and non-OOP)

Your argument reads (to me) like the quite ridiculous following statement: If you do not use OOP, and the language provides a "Procedure" that does not return a result, then you must always use such a procedure instead of function, if you want to trigger an action (including changing some value). Thus if an action can not be executed, the only way to return the error is an exception.

Quote
What good is it to have a framework if some of it has to be avoided ?
What good is it, that there is a StrToInt, if you have to avoid it?

Mind, it does not matter if it is easy to avoid or not. The point is that if it is to be avoided, then why is it there at all.


Anyway, you get the last word. As I do not have to offer anything on the original thread. So if you wish tear my statement apart.

alpine

  • Hero Member
  • *****
  • Posts: 1064
Re: What is good in using try..finally?
« Reply #84 on: October 10, 2021, 12:22:22 am »
*snip*
Here all readers should guess that you're actually talking about properties.
I'm definitely guilty of expecting the readers to know Object Pascal and be aware of properties among other things.  I guess my expectations are misplaced.

Isn't it error to try accessing e.g. TStrings.Items[ I ] with I beyond the current size of the collection?
I've never used TStrings, I'm going to guess that it is an error.  Are you using that as an example to justify the use of exceptions ?
Yes.
I'm definitely guilty of expecting the skeptics of OOP/exceptions to know Object Pascal and be aware of collections among other things.  I guess my expectations are misplaced.

What kind (myraid) of problems can cause the use of "try-except"? Please specify.
Yes, there are really a myriad but, one of them is already enough to use them only when strictly necessary and that is, it is a cross stack frame goto.  A goto that does not cross stack frames is already undesirable, one that crosses stack frames is orders of magnitud more undesirable and, you should know why.
Should I know why? No, I shouldn't. I am a novice, please explain, why?
"I'm sorry Dave, I'm afraid I can't do that."
—HAL 9000

440bx

  • Hero Member
  • *****
  • Posts: 4030
Re: What is good in using try..finally?
« Reply #85 on: October 10, 2021, 12:47:43 am »
You imply (falsely) that properties must be used for everything.
I don't believe I ever implied that.

Code that need exceptions, well it can be implemented as a method, a "function of object" that can return the error. The option of having properties is not a mandate to use nothing else but properties.
if the code isn't dealing with resources it does not manage then it shouldn't need exceptions. 

The existence of code throwing exceptions (including in properties) is not mandated by OOP, nor by the compiler, nor by the existence of properties. It is a choice.
looks like it's a "choice" a bit more common than it should be.

Only due to the use in the framework, the choice becomes limited. (for both OOP and non-OOP)
isn't limiting choices a way of forcing the remaining choices ?

Quote
What good is it to have a framework if some of it has to be avoided ?
What good is it, that there is a StrToInt, if you have to avoid it?
good question.

Mind, it does not matter if it is easy to avoid or not. The point is that if it is to be avoided, then why is it there at all.
because the functionality is useful, unfortunately, it reports errors using an exception mechanism.


Anyway, you get the last word. As I do not have to offer anything on the original thread. So if you wish tear my statement apart.
I'll make an exception and let you have the last word.  This is an Object Oriented Post (OOP)



I'm definitely guilty of expecting the skeptics of OOP/exceptions to know Object Pascal and be aware of collections among other things.  I guess my expectations are misplaced.
Considering that collections such as TString are not part of the language definition, knowing or not knowing about them is not a reflection on an individual's knowledge of Object Pascal. 

Should I know why? No, I shouldn't. I am a novice, please explain, why?
In that case, I recommend you read the book "Oh Pascal" by Doug Cooper.  Excellent book, it will answer that question for you and many more. Good reading for a novice.
(FPC v3.0.4 and Lazarus 1.8.2) or (FPC v3.2.2 and Lazarus v3.2) on Windows 7 SP1 64bit.

Warfley

  • Hero Member
  • *****
  • Posts: 1499
Re: What is good in using try..finally?
« Reply #86 on: October 10, 2021, 01:03:51 am »
I tried to avoid this whole properties-oop-exceptions discussion as I think it is completely pointless, but here is just briefly something about that.

1. Properties are not part of OOP. This is easiely proovable. If it was part of OOP, then all language that implement the whole featureset of OOP would implement this. Java is the posterboy OOP language and doesn't implement properties therefore properties are not part of OOP.
Btw. neither does the UML, which is THE formal language to specify OOP architectures.

2. Properties do not require exceptions. Properties are just syntactic sugar around functions of the form "procedure Setter(AValue: AType)" and "function Getter: AType" and thereby share the same restrictions as these. Yes a function of the form "procedure Setter(AValue: AType)" can not have a return value, so if this function would need one, you wouldn't write the function like this. Same with properties. Also it should be noted that if exceptions didn't exist it does not imply that all functions that could raise an exception need a return value. A member variable within the class could be used to indicate an error (like errno does on Linux), and rather than raising an exception inside a setter, you just set that variable and call exit.

Properties can use exceptions, that doesn't mean that they require exceptions. Not having exceptions would be a little bit more inconvinient, but you could either: 1. in this cases not use properties but custom signature setters with a return value or 2. use a variable to write in the error and check this.

Just because many people currently use exceptions here does not mean that they are required. It's like saying: "today all newly build houses are made of concrete, therefore concrete is required to build houses". The reason people use exceptions is just because they are available and make this easier than the alternatives.

3. If you want to make the argument that the OOP implementation of modern object pascal requires exceptions, then you don't need to argue about properties. Just look at classes.
Through the design of classes in modern Object Pascal, the memory management is done implicitly by the constructor and destructor. Calling the constructor will automatically return the pointer to the newly allocated memory.
This means the the constructor can not have a return value, as the return value is the self address and is added implicetly by the compiler. You have also no ability to stop the creation of the object if you encounter an error within the constructor, except if you use exceptions. So if your constructor runs into an error you need to use excpetions.
The difference to your property example is, that it is very easy to not use properties if you need a return value, simply use manual getter and setter functions. But if you use classes, you *must* use the constructor and if this can run into an error you *must* use exceptions.

That said, even this is not inherent to OOP in any shape or form. This is just how it was chosen to implement Classes in Object Pascal. This could easiely be changed by having the ability to set the return value of the constructor manually rather than automatically.
Other languages like C++, which allow for their classes to be stack allocated, don't run into that problem.

As you pointed out in your #9... agreed, and the cross-frame issue is also one I tried to mention when I first posted in this thread (#35): it's what distinguishes exceptions from try/finally. And the problems are specifically what Warfley found himself wrestling with when he was working on coroutines a few weeks ago.

I want to say that I still consider this a bug in the RTL. SetJmp/LongJmp not handling the exception state transparently means that they simply can not be used with exceptions. In C++, which also supports SetJmp/LongJmp as well as exceptions this isn't a case and these functions handle the exception state for you.

I know that there are reasons why these functions don't handle the exception state in the FPC (as they are used to implement exceptions) but I still think either these functions should support the exception state, or are not publically availabe and usable when exceptions are enabled (as there is currently no way to use them without breaking the program state), or to the very least, have the documentation state that they are basically unusable if exceptions are enabled.
As it stands these functions are currently just a landmine that will blow up on you if you try to use them.

In my understanding try..finally doesn't really handle an exception, as it re-raises it directly after executing the finally block.

Lastly I want to repeat what I've wrote a little bit earlier. Try-finally should not only be associated with exceptions. I think is a little bit because the naming (i.e. having the "try" part), but try-finally is much more than that. In fact even without exceptions try-finally would be massively useful.

A finally block is not only triggered on an exceptions but on other jumps as well, namely Exit, Break and Continue.
Code: Pascal  [Select][+][-]
  1.   while True do
  2.   begin
  3.     try
  4.       break;
  5.     finally
  6.       WriteLn('Finally');
  7.     end;
  8.   end;
This makes it massively useful. E.g. if you have a loop which creates an object in it's loop body and you exit via break or skip via continue, you can use finally to make sure that the object will be freed.
Code: Pascal  [Select][+][-]
  1. for FileName in FileNames do
  2. begin
  3.   fs := TFileStream.Create(FileName, fmOpenRead);
  4.   try
  5.     w := fs.ReadWord;
  6.     if w = 0 then
  7.       Break;
  8.     if w > 1024 then
  9.       Continue;
  10.     // long algorithm
  11.   finally
  12.     fs.Free;
  13.   end;
  14. end;

So I think assocating try-finally only with exceptions does a hughe disservice to this construct. Even in a world with no exceptions try-finally is very usefull and it is by far the feature I miss most when having to use C.
Basically it guarantees that a certain code will be executed no matter how you exit.
« Last Edit: October 10, 2021, 01:33:58 pm by Warfley »

Seenkao

  • Hero Member
  • *****
  • Posts: 550
    • New ZenGL.
Re: What is good in using try..finally?
« Reply #87 on: October 10, 2021, 03:17:35 am »
You're arguing that exception handling is bad, because it is implied by OOP, which in turn is bad, because everything can be written procedural and without objects? Did I get it right?
Нет! Нет! И ещё раз нет! )))
Не мешайте пожалуйста всё и сразу в одну кучу! (возможно я виноват своим двусмысленным высказыванием). В посте #55 я указал почему я это не использую. На что мне ответили, что я что-то делаю неправильно. Возможно MarkMLl мог оказаться правым на мой счёт, если бы на месте меня был кто-то другой. Но на моём месте - я. ))) И попробовав сделать всё то же самое что делаю я, он бы так же столкнулся с теми же проблемами. Код, с которым я работаю достаточно нативен. Я не использую LCL и многие классы (да, я не люблю ООП, но я видел немало программ которые хорошо сделаны с помощью ООП и они не сильно "раздутые" - небольшого размера). И перечитывая тему, я начал понимать, почему в моём коде не срабатывают подобное.

Для того чтоб использовать try..exception/try..finally надо включать в них вызываемый код (что обычно и происходит в ООП). А в моём коде, я проверяю не включаемый код, а конечный результат. И, я не могу использовать данные методы для проверки, потому что они не будут "пытаться" сделать. Уже всё сделано и обрабатывать уже нечего. Ошибка уже совершена (в чём-то тут моя вина, и я этого не понимал изначально).

Потому, надо смотреть, что происходит. Если вызывается процедура/функция, то её можно обработать подобным образом. Она попытается сработать, вызовет исключение и  вернётся (сделав вид, что код не сработал). И тогда ошибку обойдём. Если мы обрабатываем конечный результат, мы не сможем ни чего обработать данными методами.

Yandex translate:
No! No! And once again, no! )))
Please do not interfere all at once in one pile! (perhaps I am to blame for my ambiguous statement). In post #55 I indicated why I don't use it. To which I was told that I was doing something wrong. Perhaps MarkMLl could have been right about me if someone else had been in my place. But I am in my place.))) And if he tried to do all the same things that I do, he would also face the same problems. The code I'm working with is quite native. I don't use LCL and many classes (yes, I don't like OOP, but I've seen a lot of programs that are well made with OOP and they are not very "bloated" - small in size). And rereading the topic, I began to understand why such things do not work in my code.

In order to use try..exception/try..finally it is necessary to include the called code in them (which usually happens in OOP). And in my code, I'm not checking the included code, but the final result. And, I can't use these methods for verification because they won't "try" to do. Everything is already done and there is nothing left to process. The mistake has already been made (something is my fault here, and I didn't understand it initially).

Therefore, we need to look at what is happening. If a procedure/function is called, then it can be handled in a similar way. It will try to work, raise an exception and return (pretending that the code did not work). And then we will bypass the error. If we process the final result, we will not be able to process anything with these methods.

Quote from: y.ivanov
Then the 440bx standpoint that is actually revealed quite late into the discussion - exception handling is bad, because it is the only way to return error when assigning to a property, which is part of the Pascal implementation of OOP. Because of that developer is forced to use it, and that is presumably a bad thing.
По сути, я уже ответил на это. Это не зависит от того, какое программирование мы используем. Процедурное или ООП. Это зависит от того, что мы делаем в коде. Конечный результат так обрабатывать (как я понимаю) просто нельзя. Это создано для попытки вызова процедуры/функции или какого-то кода - что может вызвать исключение. Результат - не может вызвать исключения (код уже выполнен и мы либо уже получили исключение или код просто отработал). )))

Минус подобного подхода в том, что код может выполняться несколько раз, и ни разу не выполнится. А в "сокрытых" (вызываемых) процедурах/функциях может лежать очень немало кода... что может отнять достаточное время на обработку исключения.

Yandex translate:
In fact, I have already answered this. It doesn't depend on what kind of programming we use. Procedural or OOP. It depends on what we are doing in the code. The end result can't be processed like that (as I understand it). This is created to attempt to call a procedure/function or some code - which may cause an exception. The result is that it cannot cause exceptions (the code has already been executed and we either have already received an exception or the code just worked). )))

The disadvantage of this approach is that the code can be executed several times, and it will never be executed. And there can be a lot of code in "hidden" (called) procedures/functions... which may take up enough time to process the exception.

----------------------------------------------------------------
Благодарю всех за обсуждение подобных тем! Это вправляет иногда мозги на место. И зачастую приносит немало информации!
... жаль, что такие обсуждения со временем теряются...
Eng:
Thank you all for discussing such topics! This sometimes puts the brains in place. And often brings a lot of information!
... it's a pity that such discussions are lost over time...
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

dbannon

  • Hero Member
  • *****
  • Posts: 2796
    • tomboy-ng, a rewrite of the classic Tomboy
Re: What is good in using try..finally?
« Reply #88 on: October 10, 2021, 06:17:52 am »
OK, so I have been benchmarking TSet against AVLTree. I have a just over 2000 files in a directory, I read each one into a string and save a pointer to record containing the file content and its filename into both the AVLTree and a TSet. Repeat a 1000 times and and then do another 1000 where we stop just short of poking the pointer into the structure.

My initial "read the file" function just sets the length of a string to the file size and I point a filestream at it.  No try..finally and no exception handling.

So, having a good feel about how my benchmark code works, what if I add a try..finally and a exception handler ?

Stripped down I get

 for each run of 2k files, I add a Try..finally and it jumps to 17.7mS, and exception handler gives me 17.9mS. Repeated enough times to feel the numbers are significant.

So, yes, adding try..finally and an exception handler does slow down your code. Lets compare that to putting a FileExists() call in the loop ?  21.5mS.  And FileExists() is no guarantee that the file will open or, even that it does in fact exist. Checking i/o results uses up cycles too.

Lots of network file sharing tools lie. NFS used to be very prone to dropping a connection but the client still has the metadata. I had an end user recently using a buggy file encryption system on his windows box, try opening a file "sometimes" and it would fail, try again a mS later and all good. We could all go on ....

So, just concentration on file i/o, yes, test if the file is there (fingers crossed) or or just try opening it and, on that rare occasion where it does not work, rely on try..finally and exceptions. My numbers indicate which is a faster !

Hope you don't mind me butting in !

Davo 
Lazarus 3, Linux (and reluctantly Win10/11, OSX Monterey)
My Project - https://github.com/tomboy-notes/tomboy-ng and my github - https://github.com/davidbannon

PierceNg

  • Sr. Member
  • ****
  • Posts: 374
    • SamadhiWeb
Re: What is good in using try..finally?
« Reply #89 on: October 10, 2021, 06:31:20 am »
So, just concentration on file i/o, yes, test if the file is there (fingers crossed) or or just try opening it and, on that rare occasion where it does not work, rely on try..finally and exceptions. My numbers indicate which is a faster !

Hope you don't mind me butting in !

Davo

Try
  experiment
Finally
  reportOutcome 

Good stuff!

 

TinyPortal © 2005-2018