How do exceptions help me ? lazarus / 61-Beginners ---------------------------------------------------------------------- Nitorami · 2015-02-03 17:58 Forgive me if this is a topic that has been brought up a million times already:  I often encountered the problem of proper error handling, passing results upwards through a calling stack, creating a lot of unproductive code. I thought exceptions could help me with this but I do not undestand how. Say function A calls B which calls C which tries to allocate memory. That fails, and C raises an exception. So now ? I still have to go upwards through the calling stack, certainly B needs to know that C failed otherwise it will mess up things further, and A needs to know that B failed. In the main program, I can then deal with the exception. How would this help ? ---------------------------------------------------------------------- rvk · 2015-02-03 18:54 You need to use try/finally and try/except. The finally-part in try/finally will always be executed but any exception won't be handled and travel up. The except-part in try/except will be used to handle any exception and no exception will travel up. So make sure you use try/finally to clean up any created objects. In case of an exception the finally-part is the best place to do this. The exception will stay intact and travel up until you deal with it in an except-part. Your procedure B does not need to handle the exception as long as it has a finally part to dispose of any created objects. The exception will stay intact and go back to A A simple example: Code: [Select]procedure C; begin   Obj := TObject.Create;   try     // do something   finally     Obj.Free;     // this code will always be executed     // but any exception will just travel up   end; end; procedure B; var   Obj2: TObject; begin   Obj2 := TObject.Create;   try     C;     // do something   finally     Obj2.Free;     // ......     // this code will also always be executed     // but any exception will just travel up   end; end; procedure A; begin   try     try       B;       // do something     except       // you handle the exception here       // no exception will travel back up       on E: Exception do         Showmessage('Problem detected');     end;   finally     // ......     // this code will also always be executed     // the exception is already handled   end; end; procedure Mainprocedure; begin   try     A;     // do something   finally     // ......     // this code will also always be executed   end; end; ---------------------------------------------------------------------- Nitorami · 2015-02-03 19:33 Right, I'm beginning to see how this is meant to work. Normally, before doing anything stupid in A, for instance a division by zero, I would raise an exception, right ? Rather than having the exception raised by the actual division ? But still, I do not quite see the difference to the "old" method - I mean, I can do the same by passing ordinary return values upwards, and I do not catch the benefit of doing this via exceptions ? ---------------------------------------------------------------------- skalogryz · 2015-02-03 19:52 Quote from: Nitorami on February 03, 2015, 08:33:38 pmBut still, I do not quite see the difference to the "old" method - I mean, I can do the same by passing ordinary return values upwards, and I do not catch the benefit of doing this via exceptions ? You can read the recent discussion about exceptions vs old-school result values starting from this post and up to the end of the thread. I guess the conclusion would be - the choice is yours (either to return a value or use exceptions). Just please, be consistent ---------------------------------------------------------------------- Nitorami · 2015-02-03 20:38 Hm, I see this is discussed quite controversial. On starting to try it myself based on code examples in the fpc docs, I found that I cannot get the message out of the exception handler because it is a Class variable. Code: [Select]Type EDivException = Class (Exception); Function DoDiv (X,Y : Longint) : Integer; begin   If Y=0 then Raise EDivException.Create ('Division by Zero is imminent');   Result := X Div Y; end; begin   try     writeln (DoDiv (3,0));     writeln ('DoDiv sucessful !');   except     On EDivException do writeln (EDivException.message); //well THAT does not work because I do not have an instance of EDivException. //How do I do it ?   end; end. ---------------------------------------------------------------------- rvk · 2015-02-03 20:48 You're almost there. You need to do "on E: EDivException do writeln (E.message);". Here is a working example: (B.T.W. this will still give you a dialog in the IDE which you can dismiss or ignore permanently) Code: [Select]program Project1; uses SysUtils; Type EDivException = Class (Exception); Function DoDiv (X,Y : Longint) : Integer; begin   If Y=0 then Raise EDivException.Create ('Division by Zero is imminent');   Result := X Div Y; end; begin   try     writeln (DoDiv (3,0));     writeln ('DoDiv sucessful !');   except     on E: EDivException do writeln(E.message);   end;   readln; end. ---------------------------------------------------------------------- Nitorami · 2015-02-03 21:00 I would not have guessed that ! Can I use this construction with the colon universally to create "on the fly" instances of Class variables ? And, what do you mean by dialog in the IDE ? I use the text mode IDE and the program just runs straight through but does not pop up with a message ... ? ---------------------------------------------------------------------- rvk · 2015-02-03 21:12 Quote from: Nitorami on February 03, 2015, 10:00:50 pmCan I use this construction with the colon universally to create "on the fly" instances of Class variables ? I'm not sure what you mean by "on the fly" instances of Class variables but for exceptions this is the way to handle them (On E: EExceptionType do showmessage(E.Message). E could also be something else... but the "On" is specific to the except-part. Quote from: Nitorami on February 03, 2015, 10:00:50 pmAnd, what do you mean by dialog in the IDE ? I use the text mode IDE and the program just runs straight through but does not pop up with a message ... ? In Lazarus (graphical IDE) exceptions are also always caught by the IDE/debugger and displayed. After pressing continue the exception is forwarded to you program. You can check a box to permanently ignore a specific type of exception by the IDE so it is passed straight to your program (so usually the debugger sits in between). Outside the IDE this is not the case and the exceptions are directly passed to your program. I expect this is also how it's done in the text mode IDE. ---------------------------------------------------------------------- Nitorami · 2015-02-03 21:19 Understood. Thanks a lot guys, I really appreciate the quick help on this forim. Oh, "on the fly" - my point is that - as you say, "E could be something else" - E has in fact not been declared in the code as is usual in Pascal, it is just created "on the fly". Usually I would expect a preceding declaration like "var E: EExceptionType;" etc... ---------------------------------------------------------------------- rvk · 2015-02-03 21:27 Quote from: Nitorami on February 03, 2015, 10:19:50 pmOh, "on the fly" - my point is that - as you say, "E could be something else" - E has in fact not been declared in the code as is usual in Pascal, it is just created "on the fly". Usually I would expect a preceding declaration like "var E: EExceptionType;" etc... Yeah... The "On E: EExceptionType" is a special case here where On created E "on the fly". The exception itself is already present it's just with "On" you can specify how you're going to reference that exception in the block ahead. ---------------------------------------------------------------------- Nitorami · 2016-03-01 19:17 Yesterday in a different thread I was intimitated by some code with impressively nested try...finally blocks, and could not figure their purpose... so I concluded I have still not fully understood this. Well in theory, the idea is to clean up after an exception was raised, but I cannot see why this is necessary. In the small program below, an instance of TAtom, owned by TSystem, raises an exception in TAtom.Create - and even before the Exception message is printed, the failed TAtom and TSystem have been destroyed automatically. Who does that ? In no place did I call the destroy method. Is this part of exception handling ? But why would I then still need try...finally ? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$mode objfpc}uses heaptrc, sysutils; type TAtom = Class               X: pointer;               constructor Create (shallfail: boolean);             destructor  Destroy; override;             end; constructor TAtom.Create (shallfail: boolean);begin   writeln (' TAtom about to be created; shallfail: ',shallfail);   if shallfail then raise Exception.Create ('Gone wrong');   GetMem (X,1000);end; destructor TAtom.Destroy;begin  writeln (' TAtom about to be destroyed');  FreeMem (X);end; //------------------------------------type TSystems = Class       L1, L2: TAtom;       constructor Create;       destructor  Destroy; override;     end; constructor TSystems.Create;begin  writeln ('Creating TSystems');  L1 := TAtom.Create (false);  L2 := TAtom.Create (true);end;  destructor TSystems.Destroy;begin  writeln ('Now in TSystems.Destroy');  L1.Free;  L2.Free;end;  //------------------------------------var Sys1: TSystems;begin  writeln ('----------------------------');  try    Sys1 := TSystems.Create;    except on E:Exception do ShowException (E,ExceptAddr);  end;  readln;//  Sys1.free;end. ---------------------------------------------------------------------- Thaddy · 2016-03-01 19:25 Well, basically an exception is an  exception, which means it should not happen. The programmer is responsible for everything that can conceivably happen in his program. Exceptions are used by many because they are lazy or really know jack shit about programming. You should use an exception only and I mean really only to guard against things that are outside of your control. like file IO, Networks, Hardware failures and NOTHING else. (I am old school and hardcore...) Exceptions are very helpful in those kind of circumstances. They should not ever, never be used for anything else. ---------------------------------------------------------------------- rvk · 2016-03-02 08:31 Quote from: Nitorami on March 01, 2016, 08:17:54 pmIn the small program below, an instance of TAtom, owned by TSystem, raises an exception in TAtom.Create - and even before the Exception message is printed, the failed TAtom and TSystem have been destroyed automatically. Who does that ? In no place did I call the destroy method. Is this part of exception handling ? But why would I then still need try...finally ?To answer your question. When there is an exception in the constructor of the object, the destructor it automatically called and the creation of the object is aborted. So you always need to make sure the destructor can handle that. That's also the reason why you would do TObject.Create() outside a try/finally (where the finally cleans up the object). When the Create() fails there is nothing to clean up and with the exception there is no need to enter the try/finally block. You could handle an except in an outer try/except block or further on in your program. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i try  Obj := TObject.Create(); // ALWAYS outside the try/finally where you cleanup Obj  try    // do something with Obj which could cause an exception  finally    Obj.Free;  end;except  on E:Exception do    ShowException(E, ExceptAddr);end; ---------------------------------------------------------------------- Thaddy · 2016-03-02 08:41 Or simply do not create the object That should crash on free