12.3.3 response to a family of exceptions
Such as
On Exceptiontype do
The exception response statement can respond not only to this class of exceptions, but also to subclass exceptions. Exceptions that are not thrown by systems like Einterror, Ematherror, and so on, will respond only to their subclass exceptions. And for the Elephant
On Exception do
Such a statement will respond to any exception.
The following section of code handles the integer boundary exception separately, while the other integer exceptions are treated uniformly:
Try
{Integer operation}
Except
On Erangeerror do
{Cross-border Processing}
On Einterror do
{Other integer exception handling}
End
Because the exception is cleared after processing, the above code guarantees that the ERANGEERROR exception will not be processed more than once. If the order of two response statements is reversed, the Erangeerror exception response will never be executed.
Because the exception is cleared after processing, you need to use reserved character raise to raise a current exception when you want to handle the exception more than once.
The following code uses both exception response and exception protection. The exception response is used to set the value of the variable, and exception protection is used to free resources. A current exception is raised using raise when the exception response ends.
Var
Apointer:pointer;
Aint, Adiv:integer;
Begin
Adiv: = 0;
Getmem (Apointer, 1024);
Try
Try
Aint: = ten div adiv;
Except
On Edivbyzero do
Begin
Aint: = 0;
Raise
End
End
Finally
Freemem (Apointer, 1024);
End
End
The preceding code reflects the nesting of exception handling. Exception protection, exception responses can be nested separately or nested as shown in the example above.
Application of 12.3.5 Custom exception class
Using Delphi's anomaly class mechanism, we can define our own exception class to handle the exception in program execution. Unlike standard exceptions: this anomaly is not relative to the normal operation of the system, but to the preset state of the application. For example, enter an illegal password, the input data value is out of the set range, the calculation results deviate from the expected value, and so on.
Using custom exceptions requires:
1. Define an exception object class yourself;
2. Throw an exception yourself.