delphi try except to try finally statement usage and differences

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 in the
master self-defined method anomalies and exceptions under Delphi7 environment
handle grammatical structures and implementation

abnormal

What is unusual
program development process, there are compile errors and run-time errors, compile-time error is easy to find, and run-time error (Logical errors and exceptions) are often difficult to predict. For the stability and reliability of the program, you need to procedures for exception handling and protection.

Exception: understood as a special event, when the 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 is to facilitate users report errors and error handling mechanism 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
2 using exception error handling

Traditional method
In the earlier versions of Pascal, the programmer must use compiler switch, and the state variables and the process to detect the presence of errors.

{$ 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 detecting}
the If IOResult0 the then
{error handling code };

Use exceptions for error handling

Structured exception handling is built into the language of Delphi abnormal characteristics provide a convenient handle exceptions we are dealing with two aspects:
1. Exception handling ensures proper allocation of resources or restore any changes in the application
2 Structured Exception Handling It provides a consistent runtime error handling various types of ways for developers

Delphi7 exception handling mechanism

The basic idea is to exception handling process by providing a standardized way of software, hardware errors 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 default that is received in the application Exceptions Exception to capture before .IDE will give an "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 of intellectual block, by try and end statements package code block ensures that when a program exception occurs, the program to run properly or release resources occupied.

Delphi7 exception handling mechanism

In conventional programming, with the following pseudo-code method to check and error handler:

Perform a task
If a task is not executed correctly before the
error handling is performed
to perform the next task
before If a task is not executed correctly
perform error processing
......

Delphi7 exception handling mechanism
embodiment;

try Age: = StrToInt (Edit1.Text); ShowMessage (Format ( '% d year born', [YearOf (Now) - Age])); except on do showmessage ( 'not a valid digital input edit box! '); on ERangeError do showmessage (' enter the age of the edit box is too large ');! end; 

Exception classes
Delphi7 defined according to the type of abnormality corresponding exception class. All the base classes are Exception class exception classes.
Delphi7 built a number of exception classes, the user can also custom exception class Exception class.

Points to remember exception classes:
1. Exception class is the response of different anomalies entrance
2 familiar with the hierarchy of exception classes.

Exception Exception class

Exception class is the base class of all exceptions, it is not in a 'T' at the beginning, but beginning with 'E', which is also based on the derived class 'E' beginning.
Exception class defined in SysUtils unit.
Exception most common the method is the create method:
Constructor create (const Msg: String);
Exception.Create ( 'anomaly created my own!');
the method used to create an instance of an exception class, you can also display an error message, it may also be used this method submit an exception
raise Exception.Create ( 'I throw exception!');

Example:

try raise Exception.Create ( 'I throw exception!'); except on E: Exception do showmessage ( 'exception class name:' + E.ClassName + # 13 # 10 + 'exception message:' + E.Message) ; end; 

Delphi7 exception classes built
Delphi7 define the respective exception classes depending on the type of anomalies, yet these exception classes built Delphi7 exception class.

Divided into specific runtime library exception classes, objects and component exception class exception class three categories.

Exception-based runtime library (RTL)
library can be divided into the following exception class runtime:
1 2 integer calculation abnormality floating point arithmetic hardware error exception 3 4 5 O stack abnormality abnormality (I / O exception) 6 7 character translation exception 8 cast dummy abnormality abnormality

Integer calculation anomaly

EIntError integer calculation error (class-yl)
EDivByZero integer except 0 overflow at
EIntOverFlow integer overflow
ERangeError integer bounds

Abnormal floating-point calculations

Exception (base class) EMathError floating point
EInvalidOp invalid floating-point operation instruction
overflow Eoverflow floating point operation
underflow Eunderflow floating point operation
EZeroDivide floating point addition 0

Hardware exception

EProcessorException hardware exception (the base 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 swap file EPageFault memory manager
EGPFault GPF, generally caused by objects or uninitialized pointer
EInvalidOpCode undefined instruction processor encounters

And exception stack (I / O exception)
stack exception:

EOutOfMemory heap Not enough memory to complete the operation
EInvalidPointer tries to access an outside stack pointer
(I / O exception)
EInOutError the DOS input / output error

Character conversion / casts abnormal and abnormal dumb

Character conversion exceptions
EConvertError numbers to strings or string-to-number
word conversion error

Abnormal type conversion

EInvalidCast abnormal type conversion

Dumb abnormal

EAbort calls Abort generate an error message box is not displayed

Exception class Object
An object class is for an abnormal non abnormal component caused by the object defined
objects exception classes comprising:

1 flow exception class
2 Printing exception class
3 class abnormal pattern
4 String exception class list

Flow exception class

It refers to an abnormal flow abnormality generated during operation flows associated with the program. Base stream class exception class is EStreamError, flow abnormalities other classes are derived directly or indirectly from it.
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

Graphic anomalies

Abnormal pattern including EInvalidGraphic and
EInvalidGraphicOperation two classes are defined in the Graphics section

EInvalidGraphic an exception raised when one of the following situations:

Custom graphics file type charged image. When an application does not include a valid attempt to bitmap, picture, or metafile user
when an application attempts to load the file extension is not recognized
when the image It does not match with the format or LoadFromClipboardFormat SaveToClipboardFormat.
when an application attempts to set the image does not support the value of PixelFormat

EInvalidGraphicOperation exception when one of the following conditions occur:

Scan line to access the application does not exist in the image.
When the application is not successfully written to the image.
Application paint when the canvas is not active.
Application loaded unknown or unsupported image format.
Applications the program image is set to a value unsupported PixelFormat
can not be assigned to handle the operation.

Abnormal string list

String list of users is due to abnormal string list illegal operation initiated.
Including EStringListError, EListError, etc. Because many of the components has a property (e.g., assembly, etc. Items property Tiistbox) Tstrings abstract class, thus abnormal string list it is important in the assembly programming.

EStringListError typically generated when the string list EListError bounds exception typically occurs in the following cases:

When the index exceeds the entry list range
when the string list property set dupError Duplicates
simultaneously application tries to join a repeated character string.
When the string to the string is inserted into the sorted list.

Components exception class

Assembly responsive component exception exception class, the component is due to abnormal operation of VCL components, 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 abnormal.
Abnormalities are common illegal operation, lack of abnormal and abnormal components are three types of resources, corresponding to EInvalidOpetation, EComponentError and EOutOfResource exception class.

Cause of abnormal illegal operation are:

Parent application tries to operate some of the attributes required for the assembly of the window handle of nil.
Trying to form drag and drop operation.

Cause of abnormal components are:
Delphi can not register a component

The application can not rename a component
shortage is due to resource exception is thrown when an application tries to create a window handle and the operating system can not handle the extra allocation

Exception specific components: Many components define the corresponding component class exception.

Some typical components listed exception classes:

EMenuError abnormal, abnormality menu, the program is due to the illegal operation of the menu triggered. Memus unit defined in
EInvalidGridOperation abnormality. Illegal grid operations, such as when attempting to initiate a reference grid cell does not exist. Grids unit defined in
EDatabaseError abnormality database anomaly is due to the illegal operation of the database caused.

User-defined exception class

Create user-defined exception class method

Custom exception throw
custom exception class differences with built-in exception class
exception class objects and distinguish other types of objects
to create user custom exception class method

Exception selected as the base class, the class definition of the general method, to create custom exception class on it.
As:

type EMyException = class (Exception) // define properties or methods if desired, can be written where end; 

Throw custom exception
Delphi does 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'); 

User-defined exception class distinction and built exception class

Delphi will not automatically respond to user-defined exception class, so the user-defined exception classes require the use of the raise statement throws, while the built-in exception classes and run real anomalies corresponding to when an exception occurs, the operating system will capture this exception, Delphi notice to respond.

Exception class object is different from other classes of objects

After exception class object is created, the user need not release it, 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 the raise thrown

try ... finally statement block
. try ... finally statement block is used for Resource Conservation and Recovery system status, regardless of whether part of the operation try an exception occurs, finally part of the operation should be carried out
following syntax:

try to be protected statement finally process the statement (regardless of whether an exception occurs, must be dealt with) end; 

try ... finally statement block is mainly used for conservation

Apply to the application of the system resources (e.g., memory, graphics handle), when these resources are not required, the resource should be released promptly.
Handle: The system resources are limited, generally constitute a resource chain, the chain length is limited, when 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 (with a range of an integer)

Try ... except statement block
Try ... except for the statement block operation of error handling, the programmer can use to write to the different types of exception processing.
Exception occurs, the type of abnormality determination, correctly handle exceptions.

Try ... except the general statement block and On ... Do clause in conjunction;
syntax is as follows:

function Test (x, y: Real): Real; begin try Result: = x / y; // protected statement except on EInvalidOp do Result: = 0; // exception handling statements on EZeroDivide do Result: = 0; on EOverFlow do Result: = 0; on EUnderFlow do Result: = 0; end; end; 

Try ... except statements default exception handling block main
users generally only deal with some special exception, not handle all exceptions. For those users do not care about anomalies can use the default exceptions to handle.

try // Normal program code except on EExceptionClass do // else // default exception handling a particular type of exception handling end; 

NOTE: else it must be located in the block except the last block, any type of abnormal response

Abnormal delivery

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/delphixe/p/12375550.html