What is an exception? Why do you use it?
The so-called "exception" refers to an object of an exception class. In Delphi's VCL, all exception classes are derived from the exception class. This class declares the general behavior and nature of the exception. Most importantly, it has a message property that can report the reason for the exception to occur.
It should be emphasized, however, that exceptions are used to flag errors, but not to cause errors to occur. The exception is caused only by encountering raise, and at any time, even if no error occurs, raise will cause an exception to occur. Exceptions occur only because of raise, not others! By throwing an exception to handle an unexpected situation, you can guarantee that all code in the program's main process is available without having to add a complex judgment statement. For example, function a throws an exception:
[Delphi]View PlainCopy
- function A (): Integer;
- Vat
- Pfile:textfile;
- Begin
- ...... //Some code
- PFile: = Somefunctiontoopenanfile ();
- If PFile = nil Then
- Raise Exception. Create (′open file failed!′); //File open failed throwing exception
- Read (PFile, ...); //Read file
- ...... //Some other actions on the file, at which point the file pointer is guaranteed to be valid
- End
The code for function A makes it easy to handle file open errors. If the file fails to open, a exception class exception object is thrown, and the function returns immediately, thereby protecting the following operation against the file pointer from being executed. The thrown exception also needs to be captured and processed. Assuming that function B calls function A, to catch this file opening the failed exception, you need to preset a trap before calling a, which is called the "Try...except block". First look at the code for function B:
[Delphi]View PlainCopy
- Procedure B ();
- Begin
- ...... //Some code
- Try
- A (); //Call a
- Somefunctiondependona (); //function dependent on the result of a
- Except
- ShowMessage (′some error occured′); //Hey, I fell in, there was an anomaly .
- End;
- ...... //Continuation of the Code
- End
A throws an exception that will be captured by the try...except set by B. Once the exception is caught, the subsequent sensitive code is no longer executed, but instead immediately jumps to the except block to perform error handling before proceeding with the execution of the code after the entire try block. Control over the program flow is left in function B.
http://blog.csdn.net/sushengmiyan/article/details/7506421
Delphi Master Breakthrough exception and error handling