Turn: Delphi exception capture try except statement and try finally statement usage

Source: Internet
Author: User
Tags string to number unsupported

Ext: http://www.java123.net/v/936977.html 2015-06-24 09:27:48

have been writing procedures do not control them, and try to use very little, today finally want to get him to get a clear, find on the Internet, write down!
The main is a small part of the front, followed by a detailed description (very verbose!)

first, the source of the anomaly
in Delphi applications, the following scenarios are more likely to produce exceptions.
(1) file processing
(2) memory allocation
(3)Windows Resources
(4) creating objects and forms at run time
(5) Hardware and operating system conflicts
   
second, the treatment of abnormal
(1) try...except...end;
when the code in the try body has an exception, the system will turn to the except section for exception handling. This is one of the most basic ways in which Delphi handles exceptions.
  
(2) try...finally...end;
this exception-handling structure is typically used to protect Windows from resource allocation, and it ensures that, regardless of whether the code in the try body has an exception, some Windows objects that are processed by the system for the last uniform processing need to be handled correctly.
Unlike Try...except...end, the finally part of the structure is always executed.
  
(3) There is no try...except...finally...end structure to handle the exception, but also to protect the structure of the resource allocation, however, the try...except...end structure allows nesting into the try...finally...end structure, thus implementing both exception handling, and to protect the allocation of resources.
  
three, the precise processing of the anomaly
(1) define an exception.
in Delphi, each exception is a derived class of the exception[1] class [2].  Therefore, defining an exception is a derived class that defines a exception class.
Type emyexception = Class (Exception);
of course, a base class can be a derived class of any hierarchy of exception or exception.
  
(2) throws an exception in the program.
throwing exceptions According to different situations is the most basic pattern of using exceptions.  In Delphi, it is implemented by the raise statement.
"Syntax" Raise Exception class. Create (' Default description of Exception ');
  
(3) More precise catching of anomalies in try...except...end.
use on E: Exception class do ... Structs can handle exceptions thrown by specific exception classes in the Do body.
  
Four, the abnormal debugging
in the Delphi IDE, remove the Debugger options (you can use the menu Tools->debugger options ... The Integrated debugging checkbox in the check box allows for abnormal debugging.
  
v. Supplementary description of the exception
(1) Every paragraph of the program may produce errors! This is an indisputable phenomenon and law of the software industry. In fact, the traditional if...else ... Structure can completely solve all the errors, using the exception mechanism is not able to avoid at the most primitive level, by traversing the possible situation to produce an exception, then, why do you want an abnormal mechanism?
  
The answer is clear: exceptions provide a more flexible and open way for later programmers to handle this error based on the actual situation, rather than using pre-programmed processing results.

Delphi7 Exception Handling
Learn what exceptions are and what exception classes are available in Delphi7
Mastering the methods and exceptions of custom exceptions in the DELPHI7 environment
Syntax structure and implementation of processing

Abnormal

What is an exception
During program development, there are compile-time errors and run-time errors, compile-time errors are easy to spot, and run-time errors (logic errors and exceptions) are often difficult to predict. For the stability and reliability of the program, program exception handling and protection is required.

Exception: understood as a special event that occurs when the normal execution of the program is interrupted.
Abnormal conditions caused by a program are errors rather than exceptions, and program errors are not the same concept as exceptions.
Exceptions are mechanisms created to make it easier for users to report errors and handle errors, typically done by the operating system.
Run-time error handling

During software development, programmers must provide a modest way to handle unavoidable errors. The general method is as follows:
1 Traditional methods
2 using Exceptions for error handling

Traditional methods
In earlier versions of Pascal, programmers had to use compiler switches and state variables to detect and handle existing errors.

{$I-} {This compiler directive turns off I/o detection}
Assign (Infile,inputname);
Reset (InFile);
{$I +} {This compiler directive restores I/o detection}
If IOResult0 Then
{Error handling code};

Using Exceptions for error handling

Structured exception handling is a built-in feature of Delphi language. It is convenient for us to deal with exceptions. There are two ways to handle exceptions:
1 exception handling ensures that any resources allocated or changed in the application are properly restored.

2 Structured exception handling provides a consistent way for developers to handle various types of run-time errors

Delphi7 exception handling mechanism

DELPHI7 defines the corresponding exception class based on the exception type. The base class for all exception classes is the exception class.
Delphi7 has a large number of exception classes built into it, and users can customize the exception class through the exception class.

Remember the main points of the exception class:
1 exception classes are portals that respond to different anomalies.
2 familiar with the hierarchy of exception classes.

Exception Exception class

Exception is the base class for all exception classes, it does not start with ' T ', but begins with ' E ', and its derived classes start with ' e '.
The exception class is defined in the Sysutils cell.
The most common method of the exception class is the Create method:
Constructor Create (const msg:string);
Exception.create (' I created the exception myself! ');
This method is used to create an instance of an exception class, to display an error message, or to apply this method to commit an exception
Raise Exception.create (' I throw an exception! ');

Cases:

Delphi7 built-in exception classes
DELPHI7 defines the corresponding exception class based on the type of the exception, which is also known as the Delphi7 built-in exception class.

It is divided into three categories: Runtime Library Exception class, Object exception class and component Exception class.

Run-Time Library exception class (RTL)
The runtime library exception classes can be divided into the following types:
1 integer calculation exception 2 floating-point calculation exception 3 Hardware exception 4 heap exception 5 Input output exception (I/O exception) 6 character conversion exception 7 type conversion Exception 8 Matte exception

Integer calculation exception

Einterror integer calculation exception (base class)
Edivbyzero integer except 0 overflow
Eintoverflow integer Overflow
Erangeerror integer out of bounds

Floating-point Calculation exception

Ematherror floating-point calculation exception (base class)
EINVALIDOP Invalid floating point operation instruction
Eoverflow floating-point operation overflow
Eunderflow floating-point operation underflow
Ezerodivide floating point calculation except 0

Hardware exceptions

Eprocessorexception Hardware exceptions (base class)
ESINGLESTEP application generates single-step interrupts
Ebreakpoint Application generates breakpoint interrupt
Efault Fault (inherited Eprocessorexception, also base class)
Estackfault illegal access to the processor stack segment
Epagefault memory Manager does not use swap files correctly
Egpfault a protective error, typically caused by an uninitialized pointer or object
Einvalidopcode Processor encountered undefined instruction

The basic idea of exception handling is to make the program more robust by providing the ability to handle soft and hardware errors in a canonical manner.
Exception handling separates code that handles errors from normal logic-handling code.
The default way of Delphi is to catch an exception before the application receives an exception. The IDE gives an alert dialog box to indicate that the application will produce an exception.
Exception handling mechanism is a program design security policy, it is built on the protection block thought, through the try and end statement block to the code to ensure that the program occurs when an exception, the program can run or release the resources occupied.

Delphi7 exception handling mechanism

In traditional programming, the following pseudo-code method is used to check and handle program errors:

Perform a task
If the previous task did not execute correctly
Performing error handling
Perform the next task
If the previous task did not execute correctly
Performing error handling
......

Delphi7 exception handling mechanism
Cases

Try Age: = Strtoint (Edit1.text); ShowMessage (Format (' Born%d ', [Yearof (now)-age]); except on               

Exception class

Heap Exceptions and (I/O exceptions)
Heap Exception:

There is not enough memory in the Eoutofmemory heap to complete the operation
Einvalidpointer trying to access a pointer outside the heap
(I/O exception)
Einouterror DOS input/Output error

Character conversion/Type conversion exceptions and dumb exceptions

Character Conversion exception
Econverterror numeric to string or string to number
Word Conversion Error

Type Conversion exception

Einvalidcast Type Conversion exception

Mute exception

Eabort call Abort to generate, do not display error prompt box

Object Exception Class
The object exception class is defined for exceptions thrown by non-component objects.
Object exception classes include:

1 Stream Exception class
2 Printing Exception classes
3 Graphics Exception Class
4 String List Exception class

Stream Exception class

A stream exception is an exception that occurs when a stream-related operation is made in a program. The base class of the stream exception class is Estreamerror, and other stream exception classes are either birthday recitation or indirectly derived from it.
Derived relationship See book 48 page diagram

Printing exceptions

The printing exception is caused by the application sending a print command to a nonexistent printer or for some reason the print job cannot be delivered to the printer.
The print exception class is eprinter, defined in the Printers unit

Graphics exceptions

Graphic anomalies mainly include einvalidgraphic and
Einvalidgraphicoperation Two classes are defined on a graphics unit

Einvalidgraphic exception is thrown when one of the following conditions is true:

When an application attempts to mount an image to a file that does not contain a legitimate bitmap, image, metafile, or user-defined graphic type.
When an application tries to mount a file that is not recognized by extension
When the image does not match the format in Loadfromclipboardformat or Savetoclipboardformat.
When an application attempts to set the pixelformat of an image to an unsupported value

An einvalidgraphicoperation exception occurs when one of the following conditions is true:

When an application accesses a scan line that does not exist in the image.
When the application cannot successfully write to the image.
The application paints when the canvas is not in a valid state.
When an application loads an unknown or unsupported image format.
When an application sets the PixelFormat of an image to an unsupported value
When the handle to the operation cannot be assigned.

String List exception

The string list exception is caused by a user illegally manipulating a string list.
including Estringlisterror,elisterror and so on. Because many parts have a property that tstrings an abstract class, such as the Items property of a Tiistbox component, the string list exception is important in component programming.

Estringlisterror generally occurs when a string list is out of bounds. Elisterror exceptions typically occur in the following situations:

When an index entry is outside the list range
When the duplicates property of a string list is set to Duperror
While the application is trying to join a repeating string.
When a string is inserted into a sorted string linked list.

Component Exception Class

Component exception classes are used to respond to component exceptions, and component exceptions are caused by violating the usage rules and their characteristics of components when working with VCL components, which can be divided into two main categories:
Generic component exceptions, specialized component exceptions, generic component exceptions.
There are three types of common illegal operation exceptions, component exceptions, and resource shortages, corresponding to the Einvalidopetation,ecomponenterror and Eoutofresource exception classes.

The causes of illegal operation exceptions are:

The application attempted to do something that required a window handle on a component with the parent property of nil.
An attempt was made to drag-and-drop operations on a form.

The reasons for throwing component exceptions are:
Delphi cannot register a component

Application cannot rename a component
An out-of-resource exception is thrown because the operating system does not have an extra handle to allocate when an application tries to create a window handle

Specialized Component Exceptions: Many components define the corresponding component exception class.

Lists a few typical component exception classes:

Emenuerror exception, menu exception, is caused by the program's illegal operation on the menu. defined in MEMUs unit
Einvalidgridoperation exception. An illegal grid operation, such as an attempt to reference a non-existent grid cell, is raised. defined in Grids unit
Edatabaseerror exception. Database Exceptions are caused by illegal operation of the database.

User-defined Exception class

How to create a user-defined exception class

Throw a custom exception
User-defined exception classes differ from built-in exception classes
The difference between an exception class object and another class object
How to create a user-defined exception class

Select Exception as the base class and create a custom exception class based on the general method of defining the class.
Such as:

Throw a custom exception
Delphi does not manage the throw of user-defined exceptions, and programmers must throw their own created exceptions. Use the Raise statement to throw an exception:

User-defined exception classes differ from built-in exception classes

Delphi does not automatically respond to user-defined exception classes, so the user-defined exception class needs to be thrown with the raise statement, and the built-in exception class corresponds to the real anomaly of the runtime, and when the exception occurs, the operating system catches the exception and notifies Delphi to respond.

The difference between an exception class object and another class object

After the exception class object is created, it is not required to be released by the user, and after exception handling, the system automatically calls the destructor to release the Exception class object. Other classes need to be freed by the user.

Exception handling structure of DELPHI7

Try...finally statement block
TRY...EXCEPT statement block
Throwing exceptions using raise

Try...finally statement block
The try...finally statement block is used for resource protection and to restore the state of the system, regardless of whether or not an exception occurs in the Try section, and the finally part of the operation is performed.
The syntax is as follows:

Try...finally statement blocks are primarily used for resource protection

Applications request resources (such as memory, graphics handles) to the system, and when these resources are not needed, the resources should be released in a timely manner.
Handle: System resources are limited, generally constitute a resource chain, the length of the chain is limited, when the system assigns resources to the application, set an ID number for each resource, this ID number is the handle. (The system resource is equivalent to a room, and the handle is equivalent to the room number.)
Limited handle: 1 resources are limited; 2 The range of numbers is also limited (integer range)

TRY...EXCEPT statement block
The TRY...EXCEPT statement block is used for run-time error handling, which programmers can use to write processing for different types of exceptions.
After an exception occurs, the type of the exception is judged and the exception is handled correctly.

TRY...EXCEPT statement block general and on ... DO clause;
The syntax is as follows:

TRY...EXCEPT statement block primarily handles default exceptions
The user typically handles only a few special exceptions, not all exceptions. Exceptions that are not of interest to the user can be handled by default exceptions.

Note: The else block must be at the end of the except block to respond to any type of exception

Delivery of exceptions

Delphi's handling of exceptions is the call stack of the backward scanner. If there is a process protection code block in procedure A, in which procedure B is called, Procedure B does not have exception protection, procedure B calls procedure C, and an exception occurs within C. If there is a handler for the exception in C, Then the program calls C's exception handling code

Turn: Delphi exception capture try except statement and try finally statement usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.