SlideShare a Scribd company logo
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

More Related Content

PPTX
Exception handling
PPT
Handling
PPT
Exception handling and templates
PPT
Exception Handling
PPTX
Seh based attack
PPTX
exception handling in cpp
PPT
Comp102 lec 10
PPTX
Java - Exception Handling
Exception handling
Handling
Exception handling and templates
Exception Handling
Seh based attack
exception handling in cpp
Comp102 lec 10
Java - Exception Handling

What's hot (20)

PPT
Exceptions
PPTX
CodeChecker summary 21062021
PPT
Exception handling
PPTX
Exception handling in java
PPT
Unit iii
PPTX
Exception
PPTX
Exceptions handling in java
PPTX
Error and exception in python
PPT
Exception handling
PPT
Verilog Lecture3 hust 2014
PDF
Exception handling
PDF
Source Boston 2009 - Anti-Debugging A Developers Viewpoint
PPT
Exception Handling in JAVA
PPTX
130410107010 exception handling
PPTX
Exception handling in Java
PDF
Splint the C code static checker
PPTX
Exception handling in java
PDF
Openframworks x Mobile
PPTX
An introduction to JVM performance
PPT
Reverse engineering20151112
Exceptions
CodeChecker summary 21062021
Exception handling
Exception handling in java
Unit iii
Exception
Exceptions handling in java
Error and exception in python
Exception handling
Verilog Lecture3 hust 2014
Exception handling
Source Boston 2009 - Anti-Debugging A Developers Viewpoint
Exception Handling in JAVA
130410107010 exception handling
Exception handling in Java
Splint the C code static checker
Exception handling in java
Openframworks x Mobile
An introduction to JVM performance
Reverse engineering20151112
Ad

Viewers also liked (9)

PPT
Alllworx presentation 2
PPT
U Cx Presentation
PPTX
Pdhpe rationale
PPTX
Pensamiento administrativo
PDF
Apr9600 voice-recording-and-playback-system-with-j
PPTX
Orped anak autis
PPT
Pdhpe Rationale
PPTX
Aeonix oct2 webex lm-2 oct
PDF
Maxbox starter20
Alllworx presentation 2
U Cx Presentation
Pdhpe rationale
Pensamiento administrativo
Apr9600 voice-recording-and-playback-system-with-j
Orped anak autis
Pdhpe Rationale
Aeonix oct2 webex lm-2 oct
Maxbox starter20
Ad

Similar to A exception ekon16 (20)

PPTX
Pi j4.2 software-reliability
DOCX
Exception handling in java
PPTX
Exception Handling
PPTX
Exceptions overview
PPT
Exception Handling Exception Handling Exception Handling
PDF
22 scheme OOPs with C++ BCS306B_module5.pdf
PPTX
Exception handling c++
PPT
JP ASSIGNMENT SERIES PPT.ppt
PDF
Ch-1_5.pdf this is java tutorials for all
PPTX
Exception Handling In Java Presentation. 2024
PPTX
Java-Exception Handling Presentation. 2024
PPT
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
PDF
Presentation slides: "How to get 100% code coverage"
PPT
Exceptions in java
PPTX
Exception handling.pptxnn h
PPTX
PPTX
Exceptions in Java
PPTX
Lecture 09 Exception Handling(1 ) in c++.pptx
PPTX
Unit-4 Java ppt for BCA Students Madras Univ
Pi j4.2 software-reliability
Exception handling in java
Exception Handling
Exceptions overview
Exception Handling Exception Handling Exception Handling
22 scheme OOPs with C++ BCS306B_module5.pdf
Exception handling c++
JP ASSIGNMENT SERIES PPT.ppt
Ch-1_5.pdf this is java tutorials for all
Exception Handling In Java Presentation. 2024
Java-Exception Handling Presentation. 2024
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
Presentation slides: "How to get 100% code coverage"
Exceptions in java
Exception handling.pptxnn h
Exceptions in Java
Lecture 09 Exception Handling(1 ) in c++.pptx
Unit-4 Java ppt for BCA Students Madras Univ

More from Max Kleiner (20)

PDF
EKON28_ModernRegex_12_Regular_Expressions.pdf
PDF
EKON28_Maps_API_12_google_openstreetmaps.pdf
PDF
EKON26_VCL4Python.pdf
PDF
EKON26_Open_API_Develop2Cloud.pdf
PDF
maXbox_Starter91_SyntheticData_Implement
PDF
Ekon 25 Python4Delphi_MX475
PDF
EKON 25 Python4Delphi_mX4
PDF
maXbox Starter87
PDF
maXbox Starter78 PortablePixmap
PDF
maXbox starter75 object detection
PDF
BASTA 2020 VS Code Data Visualisation
PDF
EKON 24 ML_community_edition
PDF
maxbox starter72 multilanguage coding
PDF
EKON 23 Code_review_checklist
PDF
EKON 12 Running OpenLDAP
PDF
EKON 12 Closures Coding
PDF
NoGUI maXbox Starter70
PDF
maXbox starter69 Machine Learning VII
PDF
maXbox starter68 machine learning VI
PDF
maXbox starter67 machine learning V
EKON28_ModernRegex_12_Regular_Expressions.pdf
EKON28_Maps_API_12_google_openstreetmaps.pdf
EKON26_VCL4Python.pdf
EKON26_Open_API_Develop2Cloud.pdf
maXbox_Starter91_SyntheticData_Implement
Ekon 25 Python4Delphi_MX475
EKON 25 Python4Delphi_mX4
maXbox Starter87
maXbox Starter78 PortablePixmap
maXbox starter75 object detection
BASTA 2020 VS Code Data Visualisation
EKON 24 ML_community_edition
maxbox starter72 multilanguage coding
EKON 23 Code_review_checklist
EKON 12 Running OpenLDAP
EKON 12 Closures Coding
NoGUI maXbox Starter70
maXbox starter69 Machine Learning VII
maXbox starter68 machine learning VI
maXbox starter67 machine learning V

Recently uploaded (20)

PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
01-Introduction-to-Information-Management.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Cell Types and Its function , kingdom of life
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
master seminar digital applications in india
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Microbial disease of the cardiovascular and lymphatic systems
01-Introduction-to-Information-Management.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Cell Types and Its function , kingdom of life
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Microbial diseases, their pathogenesis and prophylaxis
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
GDM (1) (1).pptx small presentation for students
human mycosis Human fungal infections are called human mycosis..pptx
Final Presentation General Medicine 03-08-2024.pptx
master seminar digital applications in india
O5-L3 Freight Transport Ops (International) V1.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Insiders guide to clinical Medicine.pdf
Cell Structure & Organelles in detailed.
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx

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