SlideShare una empresa de Scribd logo
1 de 30
Descargar para leer sin conexión
Exception Handling
10 print “hello EKON”;
20 Goto 10;

“Exceptions measure the stability of code
before it has been written”




                                            1
Agenda EKON
• What are Exceptions ?
• Prevent Exceptions (MemoryLeakReport)
• Log Exceptions (Global Exception Handler)
• Check Exceptions (Test Driven)
• Compiler Settings




                                              2
Some Kind of wonderful ?
• One of the main purposes of exception
  handling is to allow you to remove error-
  checking code altogether and to separate error
  handling code from the main logic of your
  application.
• [DCC Fatal Error] Exception Exception:
  Compiler for personality "Delphi.Personality"
  and platform "Win32" missing or unavailable.

              UEB: 8_pas_verwechselt.txt

                                                   3
Types of Exceptions
Throwable
• Checked (Handled) Exceptions
• Runtime Exceptions (unchecked)
• Errors (system)
• Hidden, Deprecated or Silent
  EStackOverflow = class(EExternal) end deprecated;



              UEB: 15_pas_designbycontract2.txt

                                                      4
Kind of Exceptions
Some Structures
•   try finally
•   try except
•   try except finally
•   try except raise
•   Interfaces or Packages (design & runtime)
•   Static, Public, Private (inheritance or delegate)

                UEB: 10_pas_oodesign_solution.txt

                                                        5
Cause of Exceptions
Bad Coordination
• Inconsistence with Threads
• Access on objects with Null Pointer
• Bad Open/Close of Input/Output Streams or
  I/O Connections (resources)
• Check return values, states or preconditions
• Check break /exit in loops
• Access of constructor on non initialized vars



                                                  6
Who the hell is general failure
 and why does he read on my
 disk ?!
Die Allzweckausnahme!
Don’t eat exceptions   silent




                                  7
Top 5 Exception Concept
1. Memory Leak Report
•     if maxform1.STATMemoryReport = true then
•        ReportMemoryLeaksOnShutdown:= true;             Ex.
      298_bitblt_animation3
2.    Global Exception Handler Logger
3.    Use Standard Exceptions
4.    Beware of Silent Exceptions (Ignore but)
5.    Safe Programming with Error Codes

                  Ex: 060_pas_datefind_exceptions2.txt

                                                               8
Memory Leaks I
• The Delphi compiler hides the fact that the string variable is a
  heap pointer to the structure but setting the memory in advance
  is advisable:
path: string;
setLength(path, 1025);
• Check against Buffer overflow
var
 Source, Dest: PChar;
 CopyLen: Integer;
begin
 Source:= aSource;
 Dest:= @FData[FBufferEnd];
 if BufferWriteSize < Count then
   raise EFIFOStream.Create('Buffer over-run.');




                                                                     9
Memory Leaks II
• Avoid pointers as you can
• Ex. of the win32API:

pVinfo = ^TVinfo;
function TForm1.getvolInfo(const aDrive: pchar; info: pVinfo):
   boolean;
// refactoring from pointer to reference
function TReviews.getvolInfo(const aDrive: pchar; var info: TVinfo):
   boolean;

 “Each pointer or reference should be checked to see if it is null. An
  error or an exception should occur if a parameter is invalid.”



                244_script_loader_loop_memleak.txt

                                                                       10
Global Exceptions
Although it's easy enough to catch errors (or exceptions) using
"try / catch" blocks, some applications might benefit from having
a global exception handler. For example, you may want your own
global exception handler to handle "common" errors such as
"divide by zero," "out of space," etc.

Thanks to TApplication's ‘OnException’ event - which occurs
when an unhandled exception occurs in your application, it only
takes three (or so) easy steps get our own exception handler
going:




                                                                  11
Global Handling

1. Procedure AppOnException(sender: TObject;
                                 E: Exception);
 if STATExceptionLog then
    Application.OnException:= @AppOnException;




                                              12
Global Log
2. procedure TMaxForm1.AppOnException(sender: TObject;
                             E: Exception);
begin
 MAppOnException(sender, E);
end;
procedure MAppOnException(sender: TObject; E: Exception);
var
 FErrorLog: Text;
 FileNamePath, userName, Addr: string;
 userNameLen: dWord;
 mem: TMemoryStatus;




                                                            13
Log Exceptions
3. Writeln(FErrorLog+ Format('%s %s [%s] %s %s
   [%s]'+[DateTimeToStr(Now),'V:'+MBVERSION,
       UserName, ComputerName, E.Message,'at: ,Addr]));

 try
   Append(FErrorlog);
 except
   on EInOutError do Rewrite(FErrorLog);
 end;




                                                          14
Use Standards
(CL.FindClass('Exception'),'EExternal');
(CL.FindClass('TOBJECT'),'EExternalException');
(CL.FindClass('TOBJECT'),'EIntError');
(CL.FindClass('TOBJECT'),'EDivByZero');
(CL.FindClass('TOBJECT'),'ERangeError');
(CL.FindClass('TOBJECT'),'EIntOverflow');
(CL.FindClass('EExternal'),'EMathError');
(CL.FindClass('TOBJECT'),'EInvalidOp');
(CL.FindClass('EMathError'),'EZeroDivide');
"Die andere Seite, sehr dunkel sie ist" - "Yoda, halt's Maul und iß Deinen
    Toast!"




                                                                             15
Top Ten II
6. Name Exceptions by Source (ex. a:=
   LoadFile(path) or a:= LoadString(path)
7. Free resources after an exception (Shotgun
   Surgery (try... except.. finally)  pattern
   missed, see wish at the end))
8. Don’t use Exceptions for Decisions (Array
   bounds checker) -> Ex.
9. Never mix Exceptions in try… with too many
   delegating methods)        twoexcept
10. Remote (check remote exceptions, cport)
           Ex: 060_pas_datefind_exceptions2.txt

                                                  16
Testability
• Exception handling on designtime
{$IFDEF DEBUG}
 Application.OnException:= AppOnException;
{$ENDIF}
• Assert function
accObj:= TAccount.createAccount(FCustNo,
                   std_account);
assert(aTrans.checkOBJ(accObj), 'bad OBJ cond.');
• Logger
LogEvent('OnDataChange', Sender as TComponent);
LogEvent('BeforeOpen', DataSet);



                                                    17
Check Exceptions
• Check Complexity
function IsInteger(TestThis: String): Boolean;
begin
 try
   StrToInt(TestThis);
 except
   on E: ConvertError do
    result:= False;
 else
   result:= True;
 end;
end;




                                                 18
Module Tests as Checksum




                           19
Test on a SEQ Diagram




                        20
Compiler & runtime checks
 Controls what run-time checking code is generated. If such a check fails, a
run-time error is generated.  ex. Stack overflow

• Range checking
      Checks the results of enumeration and subset type
            operations like array or string lists within bounds
• I/O checking
      Checks the result of I/O operations
• Integer overflow checking
      Checks the result of integer operations (no buffer
      overrun)
• Missing: Object method call checking
      Check the validity of the method pointer prior to
      calling it (more later on).




                                                                               21
Range Checking
{$R+}
  SetLength(Arr,2);
  Arr[1]:= 123;
  Arr[2]:= 234;
  Arr[3]:= 345;
 {$R-}
Delphi (sysutils.pas) throws the ERangeError exception
ex. snippet




               Ex: 060_pas_datefind_exceptions2.txt

                                                         22
I/O Errors
The $I compiler directive covers two purposes! Firstly to include a file of
code into a unit. Secondly, to control if exceptions are thrown when an API
I/O error occurs.
{$I+} default generates the EInOutError exception when an IO error occurs.
{$I-} does not generate an exception. Instead, it is the responsibility of the
program to check the IO operation by using the IOResult routine.
 {$i-}
  reset(f,4);
  blockread(f,dims,1);
 {$i+}
  if ioresult<>0 then begin


                           UEB: 9_pas_umlrunner.txt

                                                                            23
Overflow Checks
When overflow checking is turned on (the $Q compiler
directive), the compiler inserts code to check that CPU
flag and raise an exception if it is set.  ex.
The CPU doesn't actually know whether it's added signed
or unsigned values. It always sets the same overflow flag,
no matter of types A and B. The difference is in what
code the compiler generates to check that flag.
In Delphi ASM-Code a call@IntOver is placed.



              UEB: 12_pas_umlrunner_solution.txt

                                                             24
Silent Exception, but
EStackOverflow = class(EExternal)   ex. webRobot
  end deprecated;

{$Q+} // Raise an exception to log
   try
     b1:= 255;
     inc(b1);
     showmessage(inttostr(b1));
//show silent exception with or without
   except
     on E: Exception do begin
     //ShowHelpException2(E);
     LogOnException(NIL, E);
   end;
end;


                        UEB: 33_pas_cipher_file_1.txt

                                                        25
Exception Process Steps
The act of serialize the process:
 Use Assert {$C+} as a debugging check to test
 that conditions implicit assumed to be true are
 never violated (pre- and postconditions).    ex.
 Create your own exception from Exception class
 Building the code with try except finally
 Running all unit tests with exceptions!
 Deploying to a target machine with global log
 Performing a “smoke test” (compile/memleak)



                                                    26
Let‘s practice
• function IsDate(source: TEdit): Boolean;
• begin
• try
•   StrToDate(TEdit(source).Text);
• except
•   on EConvertError do
•    result:= false;
•   else
•    result:= true;
• end;
• end;
Is this runtime error or checked exception handling ?



                                                        27
Structure Wish
The structure to handle exceptions could be improved. Even in XE3, it's
either try/except or try/finally, but some cases need a more fine-tuned
structure:

 try
   IdTCPClient1.Connect;
     ShowMessage('ok');
   IdTCPClient1.Disconnect;
 except
   ShowMessage('failed connecting');
 finally //things to run whatever the outcome
   ShowMessage('this message displayed every time');
 end;



                                                                          28
Exceptional Links:
•   Exceptional Tools:
    http://www.madexcept.com/
•   http://www.modelmakertools.com/
•   Report Pascal Analyzer:
    http://www.softwareschule.ch/download/pascal_analyzer.pdf
•   Compiler Options:
•   http://www.softwareschule.ch/download/Compileroptions_EKON13.pdf
•   Example of code with maXbox
    http://www.chami.com/tips/delphi/011497D.html
•   Model View in Together:
    www.softwareschule.ch/download/delphi2007_modelview.pdf


                              maXbox

                                                                       29
Q&A
  max@kleiner.com
www.softwareschule.ch




                        30

Más contenido relacionado

La actualidad más candente

Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in javajunnubabu
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in pythonjunnubabu
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Béo Tú
 
Source Boston 2009 - Anti-Debugging A Developers Viewpoint
Source Boston 2009 - Anti-Debugging A Developers ViewpointSource Boston 2009 - Anti-Debugging A Developers Viewpoint
Source Boston 2009 - Anti-Debugging A Developers ViewpointTyler Shields
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handlingHemant Chetwani
 
Splint the C code static checker
Splint the C code static checkerSplint the C code static checker
Splint the C code static checkerUlisses Costa
 
Openframworks x Mobile
Openframworks x MobileOpenframworks x Mobile
Openframworks x MobileJanet Huang
 
An introduction to JVM performance
An introduction to JVM performanceAn introduction to JVM performance
An introduction to JVM performanceRafael Winterhalter
 
Reverse engineering20151112
Reverse engineering20151112Reverse engineering20151112
Reverse engineering20151112Bordeaux I
 

La actualidad más candente (20)

Exceptions
ExceptionsExceptions
Exceptions
 
CodeChecker summary 21062021
CodeChecker summary 21062021CodeChecker summary 21062021
CodeChecker summary 21062021
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Exception
ExceptionException
Exception
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
Exception handling
Exception handlingException handling
Exception handling
 
Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014
 
Exception handling
Exception handlingException handling
Exception handling
 
Source Boston 2009 - Anti-Debugging A Developers Viewpoint
Source Boston 2009 - Anti-Debugging A Developers ViewpointSource Boston 2009 - Anti-Debugging A Developers Viewpoint
Source Boston 2009 - Anti-Debugging A Developers Viewpoint
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Splint the C code static checker
Splint the C code static checkerSplint the C code static checker
Splint the C code static checker
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Openframworks x Mobile
Openframworks x MobileOpenframworks x Mobile
Openframworks x Mobile
 
An introduction to JVM performance
An introduction to JVM performanceAn introduction to JVM performance
An introduction to JVM performance
 
Reverse engineering20151112
Reverse engineering20151112Reverse engineering20151112
Reverse engineering20151112
 

Destacado

Alllworx presentation 2
Alllworx presentation 2Alllworx presentation 2
Alllworx presentation 2LeeHarris217
 
Pdhpe rationale
Pdhpe rationalePdhpe rationale
Pdhpe rationale16990539
 
Apr9600 voice-recording-and-playback-system-with-j
Apr9600 voice-recording-and-playback-system-with-jApr9600 voice-recording-and-playback-system-with-j
Apr9600 voice-recording-and-playback-system-with-jicstation
 
Pdhpe Rationale
Pdhpe RationalePdhpe Rationale
Pdhpe Rationaleagrayson28
 
Aeonix oct2 webex lm-2 oct
Aeonix oct2 webex lm-2 octAeonix oct2 webex lm-2 oct
Aeonix oct2 webex lm-2 octLeeHarris217
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20Max Kleiner
 

Destacado (9)

Alllworx presentation 2
Alllworx presentation 2Alllworx presentation 2
Alllworx presentation 2
 
U Cx Presentation
U Cx PresentationU Cx Presentation
U Cx Presentation
 
Pdhpe rationale
Pdhpe rationalePdhpe rationale
Pdhpe rationale
 
Pensamiento administrativo
Pensamiento administrativoPensamiento administrativo
Pensamiento administrativo
 
Apr9600 voice-recording-and-playback-system-with-j
Apr9600 voice-recording-and-playback-system-with-jApr9600 voice-recording-and-playback-system-with-j
Apr9600 voice-recording-and-playback-system-with-j
 
Orped anak autis
Orped anak autisOrped anak autis
Orped anak autis
 
Pdhpe Rationale
Pdhpe RationalePdhpe Rationale
Pdhpe Rationale
 
Aeonix oct2 webex lm-2 oct
Aeonix oct2 webex lm-2 octAeonix oct2 webex lm-2 oct
Aeonix oct2 webex lm-2 oct
 
Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20
 

Similar a A exception ekon16

Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliabilitymcollison
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++Jayant Dalvi
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage" Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage" Rapita Systems Ltd
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in javaRajkattamuri
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptyjrtytyuu
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 

Similar a A exception ekon16 (20)

Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Anti Debugging
Anti DebuggingAnti Debugging
Anti Debugging
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage" Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage"
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
43c
43c43c
43c
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Unit iii pds
Unit iii pdsUnit iii pds
Unit iii pds
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 

Más de Max Kleiner

EKON26_VCL4Python.pdf
EKON26_VCL4Python.pdfEKON26_VCL4Python.pdf
EKON26_VCL4Python.pdfMax Kleiner
 
EKON26_Open_API_Develop2Cloud.pdf
EKON26_Open_API_Develop2Cloud.pdfEKON26_Open_API_Develop2Cloud.pdf
EKON26_Open_API_Develop2Cloud.pdfMax Kleiner
 
maXbox_Starter91_SyntheticData_Implement
maXbox_Starter91_SyntheticData_ImplementmaXbox_Starter91_SyntheticData_Implement
maXbox_Starter91_SyntheticData_ImplementMax Kleiner
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Max Kleiner
 
EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4Max Kleiner
 
maXbox Starter87
maXbox Starter87maXbox Starter87
maXbox Starter87Max Kleiner
 
maXbox Starter78 PortablePixmap
maXbox Starter78 PortablePixmapmaXbox Starter78 PortablePixmap
maXbox Starter78 PortablePixmapMax Kleiner
 
maXbox starter75 object detection
maXbox starter75 object detectionmaXbox starter75 object detection
maXbox starter75 object detectionMax Kleiner
 
BASTA 2020 VS Code Data Visualisation
BASTA 2020 VS Code Data VisualisationBASTA 2020 VS Code Data Visualisation
BASTA 2020 VS Code Data VisualisationMax Kleiner
 
EKON 24 ML_community_edition
EKON 24 ML_community_editionEKON 24 ML_community_edition
EKON 24 ML_community_editionMax Kleiner
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingMax Kleiner
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklistMax Kleiner
 
EKON 12 Running OpenLDAP
EKON 12 Running OpenLDAP EKON 12 Running OpenLDAP
EKON 12 Running OpenLDAP Max Kleiner
 
EKON 12 Closures Coding
EKON 12 Closures CodingEKON 12 Closures Coding
EKON 12 Closures CodingMax Kleiner
 
NoGUI maXbox Starter70
NoGUI maXbox Starter70NoGUI maXbox Starter70
NoGUI maXbox Starter70Max Kleiner
 
maXbox starter69 Machine Learning VII
maXbox starter69 Machine Learning VIImaXbox starter69 Machine Learning VII
maXbox starter69 Machine Learning VIIMax Kleiner
 
maXbox starter68 machine learning VI
maXbox starter68 machine learning VImaXbox starter68 machine learning VI
maXbox starter68 machine learning VIMax Kleiner
 
maXbox starter67 machine learning V
maXbox starter67 machine learning VmaXbox starter67 machine learning V
maXbox starter67 machine learning VMax Kleiner
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3Max Kleiner
 
EKON22_Overview_Machinelearning_Diagrams
EKON22_Overview_Machinelearning_DiagramsEKON22_Overview_Machinelearning_Diagrams
EKON22_Overview_Machinelearning_DiagramsMax Kleiner
 

Más de Max Kleiner (20)

EKON26_VCL4Python.pdf
EKON26_VCL4Python.pdfEKON26_VCL4Python.pdf
EKON26_VCL4Python.pdf
 
EKON26_Open_API_Develop2Cloud.pdf
EKON26_Open_API_Develop2Cloud.pdfEKON26_Open_API_Develop2Cloud.pdf
EKON26_Open_API_Develop2Cloud.pdf
 
maXbox_Starter91_SyntheticData_Implement
maXbox_Starter91_SyntheticData_ImplementmaXbox_Starter91_SyntheticData_Implement
maXbox_Starter91_SyntheticData_Implement
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475
 
EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4
 
maXbox Starter87
maXbox Starter87maXbox Starter87
maXbox Starter87
 
maXbox Starter78 PortablePixmap
maXbox Starter78 PortablePixmapmaXbox Starter78 PortablePixmap
maXbox Starter78 PortablePixmap
 
maXbox starter75 object detection
maXbox starter75 object detectionmaXbox starter75 object detection
maXbox starter75 object detection
 
BASTA 2020 VS Code Data Visualisation
BASTA 2020 VS Code Data VisualisationBASTA 2020 VS Code Data Visualisation
BASTA 2020 VS Code Data Visualisation
 
EKON 24 ML_community_edition
EKON 24 ML_community_editionEKON 24 ML_community_edition
EKON 24 ML_community_edition
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage coding
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklist
 
EKON 12 Running OpenLDAP
EKON 12 Running OpenLDAP EKON 12 Running OpenLDAP
EKON 12 Running OpenLDAP
 
EKON 12 Closures Coding
EKON 12 Closures CodingEKON 12 Closures Coding
EKON 12 Closures Coding
 
NoGUI maXbox Starter70
NoGUI maXbox Starter70NoGUI maXbox Starter70
NoGUI maXbox Starter70
 
maXbox starter69 Machine Learning VII
maXbox starter69 Machine Learning VIImaXbox starter69 Machine Learning VII
maXbox starter69 Machine Learning VII
 
maXbox starter68 machine learning VI
maXbox starter68 machine learning VImaXbox starter68 machine learning VI
maXbox starter68 machine learning VI
 
maXbox starter67 machine learning V
maXbox starter67 machine learning VmaXbox starter67 machine learning V
maXbox starter67 machine learning V
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3
 
EKON22_Overview_Machinelearning_Diagrams
EKON22_Overview_Machinelearning_DiagramsEKON22_Overview_Machinelearning_Diagrams
EKON22_Overview_Machinelearning_Diagrams
 

Último

ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 

Último (20)

ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 

A exception ekon16

  • 1. Exception Handling 10 print “hello EKON”; 20 Goto 10; “Exceptions measure the stability of code before it has been written” 1
  • 2. Agenda EKON • What are Exceptions ? • Prevent Exceptions (MemoryLeakReport) • Log Exceptions (Global Exception Handler) • Check Exceptions (Test Driven) • Compiler Settings 2
  • 3. Some Kind of wonderful ? • One of the main purposes of exception handling is to allow you to remove error- checking code altogether and to separate error handling code from the main logic of your application. • [DCC Fatal Error] Exception Exception: Compiler for personality "Delphi.Personality" and platform "Win32" missing or unavailable. UEB: 8_pas_verwechselt.txt 3
  • 4. Types of Exceptions Throwable • Checked (Handled) Exceptions • Runtime Exceptions (unchecked) • Errors (system) • Hidden, Deprecated or Silent EStackOverflow = class(EExternal) end deprecated; UEB: 15_pas_designbycontract2.txt 4
  • 5. Kind of Exceptions Some Structures • try finally • try except • try except finally • try except raise • Interfaces or Packages (design & runtime) • Static, Public, Private (inheritance or delegate) UEB: 10_pas_oodesign_solution.txt 5
  • 6. Cause of Exceptions Bad Coordination • Inconsistence with Threads • Access on objects with Null Pointer • Bad Open/Close of Input/Output Streams or I/O Connections (resources) • Check return values, states or preconditions • Check break /exit in loops • Access of constructor on non initialized vars 6
  • 7. Who the hell is general failure and why does he read on my disk ?! Die Allzweckausnahme! Don’t eat exceptions silent 7
  • 8. Top 5 Exception Concept 1. Memory Leak Report • if maxform1.STATMemoryReport = true then • ReportMemoryLeaksOnShutdown:= true; Ex. 298_bitblt_animation3 2. Global Exception Handler Logger 3. Use Standard Exceptions 4. Beware of Silent Exceptions (Ignore but) 5. Safe Programming with Error Codes Ex: 060_pas_datefind_exceptions2.txt 8
  • 9. Memory Leaks I • The Delphi compiler hides the fact that the string variable is a heap pointer to the structure but setting the memory in advance is advisable: path: string; setLength(path, 1025); • Check against Buffer overflow var Source, Dest: PChar; CopyLen: Integer; begin Source:= aSource; Dest:= @FData[FBufferEnd]; if BufferWriteSize < Count then raise EFIFOStream.Create('Buffer over-run.'); 9
  • 10. Memory Leaks II • Avoid pointers as you can • Ex. of the win32API: pVinfo = ^TVinfo; function TForm1.getvolInfo(const aDrive: pchar; info: pVinfo): boolean; // refactoring from pointer to reference function TReviews.getvolInfo(const aDrive: pchar; var info: TVinfo): boolean; “Each pointer or reference should be checked to see if it is null. An error or an exception should occur if a parameter is invalid.” 244_script_loader_loop_memleak.txt 10
  • 11. Global Exceptions Although it's easy enough to catch errors (or exceptions) using "try / catch" blocks, some applications might benefit from having a global exception handler. For example, you may want your own global exception handler to handle "common" errors such as "divide by zero," "out of space," etc. Thanks to TApplication's ‘OnException’ event - which occurs when an unhandled exception occurs in your application, it only takes three (or so) easy steps get our own exception handler going: 11
  • 12. Global Handling 1. Procedure AppOnException(sender: TObject; E: Exception); if STATExceptionLog then Application.OnException:= @AppOnException; 12
  • 13. Global Log 2. procedure TMaxForm1.AppOnException(sender: TObject; E: Exception); begin MAppOnException(sender, E); end; procedure MAppOnException(sender: TObject; E: Exception); var FErrorLog: Text; FileNamePath, userName, Addr: string; userNameLen: dWord; mem: TMemoryStatus; 13
  • 14. Log Exceptions 3. Writeln(FErrorLog+ Format('%s %s [%s] %s %s [%s]'+[DateTimeToStr(Now),'V:'+MBVERSION, UserName, ComputerName, E.Message,'at: ,Addr])); try Append(FErrorlog); except on EInOutError do Rewrite(FErrorLog); end; 14
  • 16. Top Ten II 6. Name Exceptions by Source (ex. a:= LoadFile(path) or a:= LoadString(path) 7. Free resources after an exception (Shotgun Surgery (try... except.. finally) pattern missed, see wish at the end)) 8. Don’t use Exceptions for Decisions (Array bounds checker) -> Ex. 9. Never mix Exceptions in try… with too many delegating methods) twoexcept 10. Remote (check remote exceptions, cport) Ex: 060_pas_datefind_exceptions2.txt 16
  • 17. Testability • Exception handling on designtime {$IFDEF DEBUG} Application.OnException:= AppOnException; {$ENDIF} • Assert function accObj:= TAccount.createAccount(FCustNo, std_account); assert(aTrans.checkOBJ(accObj), 'bad OBJ cond.'); • Logger LogEvent('OnDataChange', Sender as TComponent); LogEvent('BeforeOpen', DataSet); 17
  • 18. Check Exceptions • Check Complexity function IsInteger(TestThis: String): Boolean; begin try StrToInt(TestThis); except on E: ConvertError do result:= False; else result:= True; end; end; 18
  • 19. Module Tests as Checksum 19
  • 20. Test on a SEQ Diagram 20
  • 21. Compiler & runtime checks Controls what run-time checking code is generated. If such a check fails, a run-time error is generated. ex. Stack overflow • Range checking Checks the results of enumeration and subset type operations like array or string lists within bounds • I/O checking Checks the result of I/O operations • Integer overflow checking Checks the result of integer operations (no buffer overrun) • Missing: Object method call checking Check the validity of the method pointer prior to calling it (more later on). 21
  • 22. Range Checking {$R+} SetLength(Arr,2); Arr[1]:= 123; Arr[2]:= 234; Arr[3]:= 345; {$R-} Delphi (sysutils.pas) throws the ERangeError exception ex. snippet Ex: 060_pas_datefind_exceptions2.txt 22
  • 23. I/O Errors The $I compiler directive covers two purposes! Firstly to include a file of code into a unit. Secondly, to control if exceptions are thrown when an API I/O error occurs. {$I+} default generates the EInOutError exception when an IO error occurs. {$I-} does not generate an exception. Instead, it is the responsibility of the program to check the IO operation by using the IOResult routine. {$i-} reset(f,4); blockread(f,dims,1); {$i+} if ioresult<>0 then begin UEB: 9_pas_umlrunner.txt 23
  • 24. Overflow Checks When overflow checking is turned on (the $Q compiler directive), the compiler inserts code to check that CPU flag and raise an exception if it is set. ex. The CPU doesn't actually know whether it's added signed or unsigned values. It always sets the same overflow flag, no matter of types A and B. The difference is in what code the compiler generates to check that flag. In Delphi ASM-Code a call@IntOver is placed. UEB: 12_pas_umlrunner_solution.txt 24
  • 25. Silent Exception, but EStackOverflow = class(EExternal) ex. webRobot end deprecated; {$Q+} // Raise an exception to log try b1:= 255; inc(b1); showmessage(inttostr(b1)); //show silent exception with or without except on E: Exception do begin //ShowHelpException2(E); LogOnException(NIL, E); end; end; UEB: 33_pas_cipher_file_1.txt 25
  • 26. Exception Process Steps The act of serialize the process: Use Assert {$C+} as a debugging check to test that conditions implicit assumed to be true are never violated (pre- and postconditions). ex. Create your own exception from Exception class Building the code with try except finally Running all unit tests with exceptions! Deploying to a target machine with global log Performing a “smoke test” (compile/memleak) 26
  • 27. Let‘s practice • function IsDate(source: TEdit): Boolean; • begin • try • StrToDate(TEdit(source).Text); • except • on EConvertError do • result:= false; • else • result:= true; • end; • end; Is this runtime error or checked exception handling ? 27
  • 28. Structure Wish The structure to handle exceptions could be improved. Even in XE3, it's either try/except or try/finally, but some cases need a more fine-tuned structure: try IdTCPClient1.Connect; ShowMessage('ok'); IdTCPClient1.Disconnect; except ShowMessage('failed connecting'); finally //things to run whatever the outcome ShowMessage('this message displayed every time'); end; 28
  • 29. Exceptional Links: • Exceptional Tools: http://www.madexcept.com/ • http://www.modelmakertools.com/ • Report Pascal Analyzer: http://www.softwareschule.ch/download/pascal_analyzer.pdf • Compiler Options: • http://www.softwareschule.ch/download/Compileroptions_EKON13.pdf • Example of code with maXbox http://www.chami.com/tips/delphi/011497D.html • Model View in Together: www.softwareschule.ch/download/delphi2007_modelview.pdf maXbox 29