DELPHI exception handling 2

Today, when writing a program to import data from EXCEL with ADO, it appears a mistake, get a long time to fix, finally with exception handling to get rid of.
Before you import data date to be converted to date format, although a strtodate can change for the better, but the date data available, the date is empty, the conversion on the error, the better deal, plus IF statement on it. However, the pile of data, the date of the last line of data is empty, but not read out ' ", but rather null, so, strtodate conversion and wrong. Want to use the IF statement to determine an hour or two we did not get things right. The last try except to get.
Experience is: the programming process, often there will be some data conversion errors, but often had to ignore, such as in front of empty values, you can not assign ah. But a conversion error, the program does not run down, not to mention the other. Spend exception handling, you can ignore it, making the program continues to run down, without the occurrence of the error. Spend exception handling, or will appear in the compilation run-time error, you can check the "Skip same mistake next time," point to continue, you can then run any longer.
Information about exception handling posts get it back:
Delphi exception handling Detailed
defined Exception class [1] in the SysUtils unit.
[2] Delphi also supports not inherit from Exception Exception class, but I do not think that's very wise.
First, the unusual origin
  in Delphi applications, the following circumstances are more likely to produce abnormal.  
  (1) file processing  
  (2) memory allocation  
  (3) Windows resource 
  creation (4) run-time objects and forms  
  (5) hardware and operating system conflicts
   
  Second, exception handling
  (1) try ... except ... end   ;
  in vivo try abnormal code occurs, the system will turn portion except for exception handling. Delphi is one of the most basic way to handle exceptions.
  
  (2) try ... finally ... end   ;
  this structured exception handling is generally used to protect Windows resource allocation and other aspects, it ensures that a number of Windows objects regardless try the body of the code is abnormal, need to be handled by a final unified system the correct treatment.  
  And try ... except ... different end, finally the total portion of the structure is performed.
  
  (3) try ... except ... finally ... end structures both handle the exception, the protective structure and resource allocation, however, try ... except ... end configuration allows nested try ... finally ... end structure does not exist, in order to achieve both handling exceptions , but also protect the allocation of resources.
  
  Third, the precise exception handling
  (1) defines an exception.  
  In Delphi, each anomaly is Exception [1] is a class derived class [2]. Therefore, the definition of an exception is the definition of a class derived from Exception.  
  type EMyException = class (Exception);  
  Of course, the base class may be any Exception Exception or any derived class hierarchy.
  
  (2) throws an exception in the program.  
  Throwing an exception is the use of the most basic patterns of abnormal depending on the circumstances. In Delphi, implemented by the raise statement.  
  Grammar .Create raise exception classes ( 'default exception instructions');
  
  (3) try ... except ... end of the capture more accurate abnormality.  
  Use on E: ... do exception class structure specific exception class can handle exceptions thrown do in vivo.
  
  Fourth, abnormal debugging
  in the Delphi IDE, released "Debugger Options" (you can use the menu Tools-> Debugger Options ... access) check box in the state Integrated Debugging can be abnormal debugging.
  
  V. abnormal supplement
  (1) Each section of the program, errors may occur! This is a phenomenon and laws of the software industry an unquestionable. In fact, if ... else ... traditional structure can solve all the errors, use Exception mechanisms can not be avoided in the most primitive level, to produce unusual approach by traversing possible, then, why exception mechanism?
  
  The answer is clear: abnormal provides a more flexible and open manner, so that later programmers can handle this error in accordance with the actual situation, rather than using predefined processing results.

Delphi7 exception handling
to understand what is abnormal and abnormal class Delphi7 provided
grasp from abnormal method definition and exception under Delphi7 environment
handle grammatical structures and implementation of
abnormal
What is unusual
program development process, there are compile errors and run-time errors, compile period errors are easy to find, and run-time error (logical errors and exceptions) are often difficult to predict for stability and reliability of the program, you need to protect the program and exception handling.
Exception: understood as a special event, the when an event occurs, the normal program execution will be interrupted.
abnormal situation is caused by a program error instead of an exception, the exception is not bug the same concept.
anomaly for the convenience of users report errors and error handling and mechanisms created, is generally done by the operating system.
runtime error handling
Software development process, the programmer must provide an appropriate way to handle the inevitable errors following general procedure:
1 conventional method
Error handling 2 abnormality using
conventional methods
in earlier versions of Pascal, the programmer must use compiler switch, and the state variables to detect and handling errors occurring.
{$ the I -} {this compiler instructions to turn off I / O detection}
the Assign (the InFile, InputName);
the Reset (the InFile);
{$ the I +} {this compiler directive resume I / O detected }
the If IOResult0 the then
{} error handling code;
using error exception handling
structured exception handling is built into the language characteristics Delphi exception we provide a convenient exception processing is twofold:
the exception handler can ensure proper restore any application resource allocation or change.
2 structured exception handling provides a consistent way to handle all types of runtime errors developers
Delphi7 exception handling mechanism
basic idea of exception handling through the provision of standardized approach to soft, hardware error ability to make the process more robust.
exception handling process may be an error code to the normal logic processing code phases were separated.
Delphi The way the province is to capture abnormal .IDE will be given before the application receives an exception that "early warning" dialog box to indicate that the application will be an exception.
Exception handling mechanism is a programming security policy, which is based on the protection block I thought, by end statements and try to block the package code program ensures that when an abnormality occurs, the program to run properly or release resources occupied.
Delphi6 Delphi7 exception handling mechanism
In conventional programming, with the following pseudo-code method to check and error handler:
performing a task
before If a task is not executed correctly
performs an error process
is performed next task
before If a task is not executed correctly
perform error processing
......
Delphi6 Delphi7 exception handling mechanism
embodiment;
the try
Age: = StrToInt (Edit1.Text);
the ShowMessage (the Format ( '% d year born', [YearOf (Now) - Age]));
the except
oN EConvertError do
ShowMessage ( 'input edit box is not a valid number ');!
ON ERangeError do
ShowMessage (' age edit box input value is too large ');!
End;
exception class
Delphi7 define the corresponding type of abnormality based on the abnormality of all the base class exception classes are classes. . exception class
Delphi7 built a number of exception classes, the user can custom exception class by class exception.
Remember point exception class:
1 inlet exception class is different in response anomalies.
2 familiar exception class hierarchy.
exception exception class
Exception is the base class for all exception classes, it is not at the beginning, 'T' but begins with 'E', which is also based on the derived class 'E' beginning.
. Exception class defined in SysUtils unit
Exception most commonly used method is the Create method:
Constructor Create (const Msg: String);
Exception.Create ( 'anomaly created my own!');
This method is used to create an exception class instance, you can also display an error message, an exception can be submitted directly using this method
raise Exception.Create; ( 'I throw exception!')
Example:
the try
the raise Exception.Create ( 'I throw exception!');
the except
ON E: exception do
ShowMessage ( 'exception class name:' E.ClassName +
+ # 10 + # 13 is 'the abnormality information:' + e.Message);
End; Delphi7 built exception class
Delphi7 defined according to the type of the anomaly respective exception classes, these classes abnormal yet built Delphi7 exception classes.
DETAILED exception classes into runtime libraries, objects, classes and components exception class exception three categories.
runtime exception class library (RTL)
runtime library exception classes can be divided into the following:
abnormal floating point 1 2 3 integer calculation hardware error exception stack 4 O 5 abnormal abnormality (I / O exception) Exceptions Exceptions dummy 8 7 6 character conversion type conversion exception
integer calculation abnormality
calculating integer exception EIntError (base class)
EDivB yZero integer divide overflow at 0
EIntOverFlow integer overflow
ERangeError bounds integer
floating point exception
EMathError floating point exception (the base class)
EInvalidOp invalid floating-point operation instruction
overflow Eoverflow floating point operation
underflow Eunderflow floating point operation
EZeroDivide 0 calculated by dividing the floating point
hardware exception
EProcessorException hardware error (group class)
ESingleStep application generates a single-step interrupt
Ebreakpoint application generates a breakpoint interrupt
Efault fault (inherited EProcessorException, is the base class)
EStackFault illegal access to the processor stack segment
can not use the correct memory swap file EPageFault manager
EGPFault protection fault, general caused by an object or a pointer uninitialized
EInvalidOpCode processor encounters an undefined instruction
stack exception and (I / O exception)
stack exception:
EOutOfMemory stack is not enough memory to complete the operation
EInvalidPointer tries to access a pointer to the stack outside
(I / O exception)
EInOutError DOS input / output error
character conversion / abnormalities type conversion and the dummy abnormality
character conversion exceptions
EConvertError string or numeric string to the number of
word conversion error
Type conversion exception
EInvalidCast type conversion abnormality
dummy abnormality
EAbort calls Abort is generated, an error message box is not displayed
objects exception class
objects exception class is for an abnormal non-Component Object induced defined.
Object exception classes comprising:
a flow exception class
2 Printing exception classes
exception-based pattern 3
4 string list exception class
flow exception class
flow refers to an abnormal abnormality is generated during the operation related to the flow in the program. base stream class exception class is EStreamError, other streams exception class directly or indirectly from it derivation.
derivation relationship book see FIG. 48
print abnormal
printing is abnormal due application sends a print command to the printer is not present for some reason or when the print job to the printer can not be initiated.
prints exception class eprinter, defined in the unit printers
graphics abnormal
pattern abnormalities including EInvalidGraphic and
EInvalidGraphicOperation two classes are defined in the graphics section
initiator EInvalidGraphic exception when one of the following cases:
when the custom graphics application does not contain a valid attempt to bitmap, picture, or the user metafile when the charged image file type.
when the application When attempting to mount the file extension is not recognized
when the image does not match with the LoadFromClipboardFormat or SaveToClipboardFormat format
when an application tries to set the image PixelFormat unsupported values
EInvalidGraphicOperation exception when one of the following conditions occurs:
when the application to access the image scan lines do not exist
. Applications can not successfully written when the image
is drawn on the canvas when the application is not active.
Load applications into unknown or when the image format is not supported.
when the application of the image set to a value unsupported PixelFormat
can not be assigned to handle the operation.
string list abnormal
string list abnormality is due to a user operation illegal string list initiated.
including EStringListError, EListError etc. Since many members have a Tstrings abstract class attributes (e.g., Items property Tiistbox assembly etc.), abnormal string list so important in the assembly program.
EStringListError generally bounds when the string list . EListError exception is generated and typically occurs in the following cases:
when the index exceeds the entry list range
when the string list Duplicates property to dupError
. at the same time the application attempts to add a repeated character string
when a character string to the sorted list insertion string
assembly exception class
component for exception class Component should be abnormal, the abnormal component is due to VCL components operate in violation of the usage rule and characteristics of components triggered, can be divided into two categories:
generic component exception, special exception components, generic components abnormality.
Common abnormal illegal operation, lack of resources and abnormal abnormal components of three types, corresponding to EInvalidOpetation, EComponentError and EOutOfResource exception class.
Caused the cause of abnormal illegal operation are:
Parent application tries to attribute some operations require a window handle as a component of nil.
Trying to form drag and drop operation.
Cause of abnormal components are:
Delphi can not register a component
application can not rename a component of
a lack of resources abnormalities is due to be raised when the application tries to create a window handle and the operating system can not handle the extra allocation of
special component exception: many components are defined in the corresponding component exception class.
list several typical component exception class:
EMenuError abnormalities, abnormal menu , because illegal program operation menu triggered. Memus unit defined in
EInvalidGridOperation exception. initiator grid illegal operations, such as trying a reference grid cell does not exist. grids unit defined in
EDatabaseError exception. Since the database exception is illegal operation of the database caused.
user-defined exception class
to create a user-defined exception class method
throws an exception custom
user-defined exception class differences with built-in exception classes
exception class object is different from other types of objects
to create user-defined method exception class
selected as the base class exception, press General methods defined class, create custom exception class on it
like:
of the type
EMyException = class (Exception)
// when you need to define a property or method, write in here to
end; throw custom exception
Delphi will not manage user-defined exception thrown, the programmer must themselves thrown themselves created with the raise statement throws an exception:
raise EMyException.Create ( 'My Exception') ; and a user-defined exception class exception class distinction built
Delphi exception does not automatically respond to user-defined categories, the user-defined exception class requires raise statement throw, while the built- runtime exception classes and real anomalies corresponding to when an exception occurs, the operating system will capture this anomaly, inform Delphi to respond.
exception class object is different from other classes of objects
abnormal class object is created, the user does not need to release it is, when the exception processing, the system automatically calls the destructor releases exception class object, while other classes must be released by the user.
exception handling structure of Delphi7
try ... finally statement block
Try ... except statement block
using raise thrown
try ... finally block
try ... finally block is for the resource conservation and recovery system status, regardless of whether the try part of the operation exception occurs, part of the operation should be carried out finally.
the syntax is:
try
to be protected statement
finally
process the statement (regardless of whether an exception occur, must be dealt with)
End; the try ... a finally statement block is mainly used for resource protection
application system to apply the resources (E.g., memory, graphics handle), when resources are not required, it should prompt the release of resources.
Handle: The system resources are limited, generally constitute a resource chain, the chain length is limited, when the system resources allocated to the application program , a set of resources for each ID number, the ID number is the handle (system resource corresponding to a room, and the handle corresponds to the room number.).
limited handle: 1 resources are limited; 2 digital representation of the range is limited the (integer with a range)
Try ... except statement block
Try ... except statement blocks for error handling, exception handling programmers can write it to run different types of use.
After the occurrence of abnormality, determination of the type of abnormality, handle exceptions correctly.
Try ... except the general statement blocks and On ... do clause in conjunction;
syntax is as follows:
function the Test (the X-, the y-: Real): Real;
the begin
the try
the Result: the X-= / the y-; // protected statements
the except
ON EInvalidOp do the Result: = 0; // Exception handling statements
EZeroDivide do the Result ON: = 0;
ON EOVERFLOW do the Result: = 0;
ON EUnderFlow do the Result: = 0;
End;
End; the except the Try ... statement block main default exception handling
users typically only some special exception processing, the processing is not All exceptions for users who do not care about the abnormality can be employed to default exception handling.
the try
// normal program code
except
exception on EExceptionClass do // handle particular types
else // default exception handling
end; NOTE: else block except the last block it must be located, in response to any type of abnormal
abnormality transfer
Delphi exception handling of the call stack is a backward scanning program. If there process within Process A protection code blocks, the code block in turn calls the process B, process B is no fault protection, procedure B calls procedure C, the an abnormality occurs in the C. as the exception processing program in C, the program calls exception handling code C

Guess you like

Origin www.cnblogs.com/blogpro/p/11345996.html