Delphi Language Guide Delphi for Microsoft Win32 Delphi for the Microsoft. Net framework



Yüklə 0,84 Mb.
Pdf görüntüsü
səhifə187/294
tarix02.01.2022
ölçüsü0,84 Mb.
#41395
1   ...   183   184   185   186   187   188   189   190   ...   294
DelphiLanguageGuide

Raising and Handling Exceptions
To raise an exception object, use an instance of the exception class with a raise statement. For example,
raise EMathError.Create;
In general, the form of a raise statement is
raiseobjectataddress
where object and at address are both optional. When an address is specified, it can be any expression that evaluates
to a pointer type, but is usually a pointer to a procedure or function. For example:
raise Exception.Create('Missing parameter') at @MyFunction;
Use this option to raise the exception from an earlier point in the stack than the one where the error actually occurred.
When an exception is raised - that is, referenced in a raise statement - it is governed by special exception-handling
logic. A raise statement never returns control in the normal way. Instead, it transfers control to the innermost
exception handler that can handle exceptions of the given class. (The innermost handler is the one whose 
try...
except
 block was most recently entered but has not yet exited.)
161


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.

Yüklə 0,84 Mb.

Dostları ilə paylaş:
1   ...   183   184   185   186   187   188   189   190   ...   294




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin