Introduction
In the process of running a program, there are often some unexpected error states that cause the program to not run down. Therefore, when implementing the program function, we must consider how to deal with the various abnormal situations that may occur during the process of running the program. The so-called exception is to interrupt the normal flow of the program, very see or unexpected state, open the file by path can not find the file, unable to allocate the required memory. Now I combine the reality on the emergence of Delphi, the source and the implementation of the method of exception handling.
Source of the exception
Exceptions can be generated by a number of different resources, the user's program can be caused by abnormal state of the exception, Delphi components can be caused by different events, the value of the cross-boundary to attribute or try to create an index of nonexistent array elements, running library procedures and functions can also produce an exception, Performing a mathematical expression with an illegal operation, such as being 0 is definitely an exception. Other examples of unusual operations include referencing an nil pointer to an expression that performs an illegal type conversion, and so on. In general, the situation encountered by the software in the course of operation is very different, so the situation that produces the exception also varies.
Traditional method of exception handling
The traditional processing method is mainly controlled by the IF statement, the Boolean flag and the return value of the special function. If you are loading a file, use a conditional statement to handle an error that might result in opening the empty file.
If Opendialog.Filename=nil then //判断是否选择文件
Begin
ShowMessage(“ 选择文件无效,请重新选择一个文件”) ;
End;
The above example is the prompt for a new operation after the exception event is judged by an if statement. This exception handling method is certainly easy to understand, but in the process of software writing, if every place uses if statements to check errors and handle exceptions, making programming work more complex. In Delphi, this problem can be used in a more convenient way to implement exception handling.
The method of exception handling in Delphi
Delphi supports a variety of exception handling mechanisms, and Object Pascal provides advanced exception handling mechanisms. Here we discuss two methods of exception handling: