SlideShare uma empresa Scribd logo
1 de 30
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014
Bé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 Viewpoint
Tyler Shields
 

Mais procurados (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
 

Destaque

Alllworx presentation 2
Alllworx presentation 2Alllworx presentation 2
Alllworx presentation 2
LeeHarris217
 
Pdhpe rationale
Pdhpe rationalePdhpe rationale
Pdhpe rationale
16990539
 

Destaque (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
 

Semelhante a A exception ekon16

Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
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
HayomeTakele
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
yjrtytyuu
 
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
rohitgudasi18
 

Semelhante 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 Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
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
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling 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
 
Lecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptxLecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptx
 
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
 

Mais de Max Kleiner

Mais 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

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Último (20)

REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.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