Exception Handling in Delphi

Source: Internet
Author: User

Reprint: http://www.cnblogs.com/doit8791/archive/2012/05/08/2489471.html

Previously written Delphi program has been not aware of exception handling, the mechanism of its exception handling is always smattering, yesterday, a bug in the program, let me have a more in-depth understanding of the anomaly, you must be able to produce an abnormal place to deal with the exception, or it may cause disaster to the program .

Just like yesterday, because the write FileCopy function did not do the exception capture processing, causing the copying file error when the entire program crashes, the user can only kill the process to restart the program and other operations. later on the process of exception handling, encountered an accident just prompt the user, and then can continue to run, performance is very perfect, just realize the importance of exception handling , so to summarize the Delphi exception processing related knowledge

Introduction to Delphi's mechanism of exception handling

The Delphi exception handling mechanism is based on the concept of the protection block (protected blocks). The so-called protection block is a piece of code that is encapsulated with the reserved word try and end. The purpose of the protection block is to automatically create an appropriate exception class (Exception) when an application error occurs. The program can capture and process this exception class to ensure that the program ends properly and that the resources are freed and data is not compromised . If the program does not process, a message box is provided automatically. Every program is likely to produce errors! This is an indisputable phenomenon and law of the software industry.

The traditional way of handling errors and the connection and difference between exception handling

In fact, the traditional if...else ... The 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, but the exception provides a more flexible and open way, so that the later programmers can deal with this error according to the actual situation, Instead of using pre-programmed processing results

First, the source of the anomaly

In Delphi applications, the following conditions are more likely to produce an exception

1) file processing

2) Memory allocation

3) Windows resources

4) creating objects and forms at run time

5) Hardware and operating system conflicts

Second, exception handling

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. The Try statement block indicates code that requires exception protection. If something unusual happens in this section, an exception object is thrown. Except is the exception handling section, the exception object thrown by the protected part will execute < exception handling statements > or be captured and processed by this part of the code

Try: Except. The general format of the end statement is as follows

Try  //try protected block block    except  //exception handling block    exception handling statement (do not execute if exception does not occur) end;

Or

Try  //try Protection code block protected    statement except  //exception handling block    on < Exception handling object type 1> do < statement 1>  //Capture exception object of the specified type for processing    on < Exception handling object type 2> do < statement 2>  //Captures exception object of the specified type, processing    else        < statement n+1>    //default exception handling code end ;

  

2. Try ... finally ... end;

This exception-handling structure is typically used to protect Windows from resource allocation, and it ensures that the correct handling of some Windows objects that are handled by the system for the final unified processing, regardless of whether the code in the try body has an exception, is required

Unlike try ... except. End, the finally part of the structure is always executed. In the try-finally statement, when the try part produces an exception, the application executes the resource release statement of the finally part directly

The general format of the try finally statement is as follows

Try  //try Protection code block    protected Statement finally  //exception handling block    exception handling statement//    the end must be processed regardless of whether the exception occurred;

When used to create a resource protection block, its format can be written as:

(Allocating system resources) try    (statement using system resources) finally    (frees system resources) end;

  

3. No try ... except ... end structure to handle exceptions and to protect the structure of resource allocations

  However, the try ... except end structure allows nesting into the try ... finally ... end structure, thus implementing both exception handling and resource allocation

4. Raise: Know some of the circumstances are unreasonable, the Direct Manual Bullet Exception dialog box.

Like what

Raise Exception class. Create (' Default description of exception ');

  

5. Try ... finally structure and try ... the except structure has the following main differences in usage

1) for Try ... Finally, the finally section is always executed, regardless of whether the code in the TRY section triggers an exception. If an exception occurs, skip ahead to the finally part. And for Try ... Except structure, the code for the except section is executed only if an exception is triggered.

2) in the try ... except structure, the exception object is disposed after the exception is processed, unless the exception is re-triggered. In the Try ... finally structure, the timely finally part of the exception is handled, the exception object still exists

3) The finally section cannot handle a particular exception because it does not have a try ... exception handle in the except structure and cannot know the exact exception type. Therefore, in the finally section only the exception can be treated in general

4) In the Try ... finally structure, if you invoke the standard command exit, break, or continue in the Try section, the execution of the program will be skipped to the finally part. The finally section does not allow the invocation of the above three commands

Third, the exception class structure in Delphi

All exception classes provided by Delphi are subclasses of exception. Users can also derive a custom exception class from exception. That is, exception is the base class for all exception classes, and it does not start with ' T ', but begins with ' E ', and its derived classes start with ' e '.

Delphi provides a very large anomaly class system, which can divide exception classes into runtime exceptions, object exceptions, and component exceptions.

1. Run-Library Exception class (RTL Exception)

The runtime exception classes can be categorized into seven classes, which are defined in the Sysutils library unit

1.1. I/O exceptions

The I/O Exception class Eioouterror is generated after an attempt to operate on a file or peripheral in a program run, and it derives a public data member ErrorCode from Exception to hold the code for the error that occurred. This member can be used to take different strategies for different situations after I/O exceptions occur

When the compile instruction {$I-} is set, the I/O exception class is not generated but the error code is returned to the pre-defined variable IOResult

1.2 Heap Exceptions

Heap exceptions are generated in dynamic memory allocations, including two Lei eoutofmemory and Einvalidpointer, as shown in the following table

Heap Exception class Trigger conditions, cause
Eoutofmemory There are not enough controls to satisfy the required memory allocation
Einvalidpointer Illegal pointers. This is usually caused by a program attempting to release a pointer that has been released.

1.3 Integer Exceptions

An integer exception is derived from a Einterror class, but it is always the subclass of its class that is thrown in the program's run: Efivbyzero,erangeerror,eintoverflow, as in the following table

Exception class Trigger condition
Edivbyzero Tried to be 0 apart
Erangeerror Integer expression out-of-bounds
Eintoverflow Integer operation overflow

Erangeerror raised when the value of an integer expression exceeds the range assigned by a particular integer type. For example, the following code throws a Erangeerror exception

Exception Handling in Delphi

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.