Delphi exception capture try except statement and try finally statement usage

Source: Internet
Author: User
Tags finally block integer division string to number unsupported
I haven't bothered to write programs, and I try to use them as rarely as possible. Today I finally want to make him understand, find it online, and write down!
Mainly the small part in the front, and the detailed description in the back (very embarrassing!)

First, the source of the anomaly
In Delphi applications, the following situations are more likely to cause exceptions.
(1) File processing
(2) Memory allocation
3 (3) Windows resources
(4) Create objects and forms at runtime
(5) Hardware and operating system conflict

Second, exception handling
(1) try… except… end;
 When an exception occurs in the code in the try body, the system will turn to the except part for exception handling. This is one of the most basic ways Delphi handles exceptions.

(2) try ... finally ... end;
This kind of exception processing structure is generally used to protect the resource allocation of Windows, etc. It ensures that no matter whether the code in the try body is abnormal, the system needs to perform the final unified processing of some Windows objects correctly.
Unlike try ... except ... end, the finally part of the structure is always executed.

(3) There is no try ... except ... finally ... end structure to both handle exceptions and protect resource allocation structure, but try ... except ... end structure allows nesting in try ... finally ... end structure to achieve both exception handling And protect the allocation of resources.

Third. Accurate Handling of Exceptions
(1) Define an exception.
 In Delphi, each exception is a derived class [2] of the Exception [1] class. Therefore, defining an exception is defining a derived class of the Exception class.
Type EMyException = class (Exception);
Of course, the base class can be any Exception or any level of derived class.

(2) An exception is thrown in the program.
 Throwing exceptions according to different situations is the most basic mode of using exceptions. In Delphi, it is implemented by the raise statement.
[Syntax] raise exception class. Create (‘default description of exception’);

(3) More accurately catch exceptions in try ... except ... end.
Using on E: exception class do ... structure can handle exceptions thrown by specific exception classes in the do body.

Fourth. Exception debugging
In the Delphi IDE, you can uncheck the Integrated Debugging check box in "Debugger Options" (you can access it by using the menu Tools-> Debugger Options ...) to debug abnormally.

Fifth, supplementary explanation of abnormal
(1) Every program may produce errors! This is an unquestionable phenomenon and law in the software industry. In fact, the traditional if ... else ... structure can completely solve all errors, and the Exception mechanism has not been able to avoid the practice of generating exceptions by traversing the possible situations at the most primitive level. So, why do we need exception mechanisms?

The answer is clear: exceptions provide a more flexible and open way for later programmers to handle such errors based on actual conditions, rather than using pre-set processing results.

Delphi7 exception handling
Understand what are exceptions and the exception classes provided in Delphi7
Master the methods and exceptions of custom exceptions in Delphi7
Syntactic Structure and Implementation

Exception

What is Exception
During program development, there are compile-time errors and run-time errors. Compile-time errors are easy to find, and run-time errors (logical errors and exceptions) are often difficult to predict. For program stability and reliability, it is necessary to make exceptions Handle and protect.

Exception: It is understood as a special event.When this event occurs, the normal execution of the program will be interrupted.
The abnormal situation caused by a program is an error instead of an exception, and a program error is not the same concept as an exception.
Exceptions are a mechanism created for the convenience of users to report errors and handle errors, and are generally done by the operating system.
Run-time error handling

During software development, programmers must provide a modest way to deal with inevitable errors. The general method is as follows:
1 Traditional method
2 Error handling with exceptions

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

{$ I-} {This compiler instruction turns off I / O detection}
Assign (InFile, InputName);
Reset (InFile);
{$ I +} {This compiler instruction resumes I / O detection}
If IOResult0 then
{Error handling code};

Error handling with exceptions

Structured exception handling is a built-in feature of the Delphi language. It provides us with convenience in handling exceptions. There are two aspects to handling exceptions:
1 Exception handling ensures proper recovery of any resources allocated or changed in the application.
2 Structured exception handling provides developers with a consistent way to handle various types of runtime errors

Delphi7 exception handling mechanism

The basic idea of exception handling is to make the program more robust by providing a standardized way to handle software and hardware errors.
Exception handling can separate code that handles errors from normal logic handling code.
Delphi's default method is to catch the exception before the application receives the exception. The IDE will give a "warning" dialog to indicate that the application is about to generate an exception.
The exception handling mechanism is a program design security strategy.It is based on the idea of protection blocks.The encapsulation of code through try and end statement blocks ensures that when a program exception occurs, the program can run normally or release the occupied resources.

Delphi7 exception handling mechanism

In traditional programming, the following pseudocode methods are used to detect and handle program errors:

Perform a task
If the previous task failed to execute correctly
Perform error handling
Perform the next task
If the previous task failed to execute correctly
Perform error handling
...

Delphi7 exception handling mechanism
example;

try Age: = StrToInt (Edit1.Text); ShowMessage (Format ('born in% d years', [YearOf (Now)-Age])); except on do showmessage (' The input edit box is not a valid number! '); on ERangeError do showmessage (' The age value in the input edit box is too large! '); end;
Exception class
Delphi7 defines the corresponding exception class according to the exception type. The base class of all exception classes is the Exception class.
Delphi7 has a large number of built-in exception classes, and users can also customize exception classes through the Exception class.

Points to remember about exception classes:
1 Anomaly classes are the entrance to respond to different anomalies.
2 Familiarize yourself with the hierarchy of exception classes.

Exception

Exception is the base class of all exception classes. It does not start with 'T', but starts with 'E'. Its derived classes also start with 'E'.
The Exception class is defined in the SysUtils unit.
The most commonly used 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 the exception class.It can also display error messages, or you can use this method to submit an exception directly.
raise Exception.Create (‘I throw an exception!’);

example:

try raise Exception.Create ('I throw an exception!'); except on E: Exception do showmessage ('Exception class name:' + E.ClassName + # 13 # 10 + 'Exception information:' + E.Message) ; end;
Delphi7 built-in exception class
Delphi7 defines corresponding exception classes according to the types of abnormal phenomena.These exception classes are also called Delphi7 built-in exception classes.

Specifically divided into three categories: runtime library exception classes, object exception classes and component exception classes.

Runtime Library Exception Class (RTL)
The runtime library exception classes can be divided into the following:
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 Dumb exception

Integer calculation exception

EIntError Integer calculation exception (base class)
EDivByZero integer division by 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 divided by 0

Hardware exception

EProcessorException hardware exception (base class)
ESingleStep application generates a single step interrupt
Ebreakpoint application generates a breakpoint interrupt
Efault fault (inherited from EProcessorException, also the base class)
EStackFault illegal access to the processor stack segment
EPageFault memory manager does not use swap files correctly
EGPFault protective fault, usually caused by uninitialized pointer or object
EInvalidOpCode processor encountered an undefined instruction

Heap exception and (I / O exception)
Heap exception:

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

Character conversion / type conversion exception and dummy exception

Character conversion exception
EConvertError number to string or string to number
Word conversion error

Type conversion exception

EInvalidCast type conversion exception

Dumb exception

EAbort is generated by calling Abort without displaying an error message box

Object exception class
Object exception classes are defined for exceptions raised by non-component objects.
Object exception classes include:

1 Stream exception class
2 print exception class
3 Graphic exception class
4 String linked list exception class

Stream exception class

A stream exception refers to an exception that occurs when a stream-related operation is performed in a program. The base class of a stream exception class is EStreamError, and other stream exception classes are derived directly or indirectly from it.
Derivative relationship see picture on page 48

Printing is abnormal

The printing exception is caused when the application sends a print command to a non-existent printer or the print job cannot be sent to the printer for some reason.
The printing exception class is Eprinter, which is defined in the Printers unit

Graphic exception

Graphic exceptions mainly include EInvalidGraphic and
EInvalidGraphicOperation both classes are defined in the Graphics unit

The EInvalidGraphic exception is raised when one of the following conditions is true:

When an application tries to load an image into a file that does not contain a valid bitmap, image, metafile, or user-defined graphic type.
When an application tries to load a file with an unrecognized extension
When the image does not match the format in LoadFromClipboardFormat or SaveToClipboardFormat.
When an application tries to set the PixelFormat of an image to an unsupported value

The EInvalidGraphicOperation exception occurs when one of the following conditions is met:

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

String linked list exception

The string linked list exception is caused when the user performs an illegal operation on the string linked list.
Including EStringListError, EListError, etc. Since many parts have a property of the Tstrings abstract class (such as the Items property of the Tiistbox component, etc.), the string linked list exception is very important in component programming.

EStringListError usually occurs when the string list is out of bounds. EListError usually occurs in the following situations:

When the index entry is out of range of the linked list
When the Duplicates property of a string linked list is set to dupError
At the same time when the application tries to join a duplicate string.
When inserting a string into a sorted list of strings.

Component exception class

The component exception class is used to respond to component exceptions. Component exceptions are caused by violations of component usage rules and their characteristics when operating VCL components, and can be divided into two major categories:
Common component exception, dedicated component exception, generic component exception.
There are three common types of illegal operation exceptions, component exceptions, and insufficient resource exceptions, corresponding to the EInvalidOpetation, EComponentError, and EOutOfResource exception classes.

The causes of illegal operation exceptions are:

The application attempted to perform some operation on the component whose parent property is nil that requires a window handle.
Tried to drag and drop the form.

Component difference

Common reasons are:
Delphi cannot register a component

Application cannot rename a component
An under-resource exception was raised because when the application tried to create a window handle and the operating system had no extra handles to allocate

Dedicated component exceptions: Many components have corresponding component exception classes defined.

List a few typical component exception classes:

EMenuError, menu exception, is caused by the program's illegal operation on the menu. Defined in the Memus unit
EInvalidGridOperation exception. Illegal grid operation, such as when trying to reference a non-existing grid cell.
EDatabaseError. A database exception was caused by an illegal operation on the database.

User-defined exception class

Methods for creating user-defined exception classes

Throw custom exception
Differences between user-defined exception classes and built-in exception classes
Difference between exception class objects and other class objects
Methods for creating user-defined exception classes

Select Exception as the base class, and follow the general method of defining a class to create a custom exception class.
Such as:

type EMyException = class (Exception) // When you need to define a property or method, write here to end;
Throw custom exception
Delphi does not manage the throwing of user-defined exceptions. Programmers must throw their own exceptions. Use raise statements to throw exceptions:

raise EMyException.Create (‘My Exception‘);
Differences between user-defined exception classes and built-in exception classes

Delphi does not automatically respond to user-defined exception classes, so user-defined exception classes need to be thrown using raise statements, and the built-in exception classes correspond to real-time exceptions. This exception informs Delphi to respond.

Difference between exception class objects and other class objects

After the exception class object is created, it does not need to be released by the user. After the exception is handled, the system will automatically call the destructor to release the exception class object. Other classes need to be released by the user.

Delphi7 exception handling structure

try ... finally block
Try ... except block
Using raise to throw an exception

try ... finally block
The try ... finally block is used to protect resources and restore the system state. Regardless of whether an exception occurs in the operation of the try part, the operation of the finally part must be performed.
The syntax is as follows:

try protected statement finally handles the statement (regardless of whether an exception occurs, it must be processed) end;
try ... finally block is mainly used for resource protection

The application requests resources from the system (such as memory, graphics handles), and when these resources are not needed, they should be released in a timely manner.
Handle: System resources are limited and generally constitute a resource chain. The length of the chain is limited. When the system allocates resources to applications, an ID number is set for each resource, and this ID number is the handle. Each room, and the handle is equivalent to the room number.)
Limited handles: 1 resources are limited; 2 the range of numeric expressions is also limited (integers have ranges)

Try ... except block
The Try ... except block is used for runtime error handling, and programmers can use it to write different types of exceptions.
After an exception occurs, determine the type of exception and handle the exception correctly.

Try ... except block is generally used with On ... Do clause;
The 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 statement on EZeroDivide do Result: = 0; on EOverFlow do Result: = 0; on EUnderFlow do Result: = 0; end; end;
Try ... except statement block mainly handles default exceptions
Users generally only handle some special exceptions, not all exceptions. For exceptions that the user does not care about, you can use the default exception to handle them.

try // normal program code except on EExceptionClass do // handle specific types of exception else // default exception handling end;
Note: the else block must be at the end of the except block and can respond to any type of exception

Exception delivery

Delphi's way of handling exceptions is to scan the program's call stack backwards. If there is a process protection code block in process A, and then process B is called in this code block, process B has no exception protection, and process B calls process C. An exception occurred in C. If there is an exception handler in C, then the program calls C's exception handling code

Delphi exception catch 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.