For example, the function below converts a string to an integer, raising an ERangeError
exception if the resulting
value is outside a specified range.
function StrToIntRange(const S: string; Min, Max: Longint): Longint;
begin
Result := StrToInt(S); // StrToInt is declared in SysUtils
if (Result < Min) or (Result > Max) then
raise ERangeError.CreateFmt('%d is not within the valid range of %d..%d', [Result,
Min, Max]);
end;
Notice the
CreateFmt method called in the raise statement. Exception and its descendants have special constructors
that provide alternative ways to create exception messages and context IDs.
A raised exception is destroyed automatically after it is handled. Never attempt to
destroy a raised exception
manually.
Note:
Raising an exception in the initialization section of a unit may not produce the intended result. Normal
exception support comes from the
SysUtils
unit, which must be initialized before such support is available.
If an exception
occurs during initialization, all initialized units - including
SysUtils
- are finalized and the
exception is re-raised. Then the exception
is caught and handled, usually by interrupting the program.
Similarly, raising an exception in the finalization section of a unit may not lead to the intended result if
SysUtils
has already been finalized when the exception has been raised.
Dostları ilə paylaş: