When the
reserved word raise occurs in an exception block without an object
reference following it, it raises whatever exception is handled by the block.
This allows an exception handler to respond to an error in a limited way and
then re-raise the exception. Re-raising is useful when a procedure or function
has to clean up after an exception occurs but cannot fully handle the
exception.
For
example, the GetFileList function allocates a TStringList object
and fills it with file names matching a specified search path:
function
GetFileList(const Path: string): TStringList;
var
I: Integer;
SearchRec: TSearchRec;
begin
Result := TStringList.Create;
try
I := FindFirst(Path, 0,
SearchRec);
while I = 0 do
begin
Result.Add(SearchRec.Name);
I :=
FindNext(SearchRec);
end;
except
Result.Free;
raise;
end;
end;
GetFileList creates a TStringList object, then uses the FindFirst and FindNext functions (defined in SysUtils) to initialize it. If the initialization fails, for example because the search path is invalid, or because there is not enough memory to fill in the string list - GetFileList needs to dispose of the new string list, since the caller does not yet know of its existence. For this reason, initialization of the string list is performed in a try...except statement. If an exception occurs, the statement’s exception block disposes of the string list, then re-raises the exception.
Raising and handling
exceptions
当保留字raise出现在异常块而没有跟随任何对象引用时,引发的任何异常都会被块处理。这就使得异常处理程序以有限的途径响应错误而再引发异常。当过程或函数必需在异常出现后清除并且不能完全处理异常时,对异常进行再引发是有用的。
例如,GetFileList函数数分配了一个TStringList对象并且填入与指定搜索路径相匹配的文件名:
function
GetFileList(const Path: string): TStringList;
var
I: Integer;
SearchRec: TSearchRec;
begin
Result := TStringList.Create;
try
I := FindFirst(Path, 0,
SearchRec);
while I = 0 do
begin
Result.Add(SearchRec.Name);
I :=
FindNext(SearchRec);
end;
except
Result.Free;
raise;
end;
end;
上面的例子中,GetFileList函数创建一个TStringList对象,然后用FindFirst和FindNext函数(定义在SysUtils单元)对其进行初始化。如果初始化失败,例如由于搜索路径无效,或者由于没有足够的内存来填入串列表 - GetFileList函数需要释放新的串列表,因为调用者还不知道其存在。鉴于以上原因,在try...except语句中执行串列表的初始化。如果异常发生,那么语句的异常块将释放串列表,然后再引发异常。