异常常用在硬件、内存、I/O和操作系统错误中。
try
AssignFile(F,FileName);
Reset(F);
except
on Exception do ...
end;
定义并声明一个异常:
function StrToIntRange(const S:string;Min,Max: Longint) : Longint;
begin
Result := StrToInt(S);
if (Result < Min) or (Result > Max) then
raise ERangeError.CreateFmt('%d is not within the valid range of %d..%d',[Result,Min,Max]);
end;
语法:
try
X := Y/Z;
except
on EZeroDivide do HandleZeroDivide;
end;
或
try
...
except
on EZeroDivide do HandleZeroDivide;
on EOverflow do HandleOverflow;
on EMathError do HandleMathError;
else
HandleAllOther;
end;
Re-raising exception(重新引发一个异常)
function GetFileList(const Path: string): TStringList;
var
I: Integer;
SearchRec: TSearchRec;
begin
Result := TStringList.Create;
try
I:= FindFirst(Path,0,SearchList);
While I = 0 do
begin
Result.Add(SearchRec.Name);
I := FindNext(SearchRec);
end;
except
Result.Free;
raise;
end;
end;
Nested Exception(内嵌异常)
type
ETrigError = class(EMathError);
function Tan(X : Extended) : Extended;
begin
try
Result := Sin(X) /Cos(X);
except
on EMathError do
raise ETrigError.Create('Invalid argument to Tan');
end;
end;
try……finally
Reset(F);
try
... //process file F
finally
CloseFile(F);
end;
经常在开发中用到的是以下这种模式即try...except...finally
procedure TForm1.Button1Click(Sender: TObject);
begin
try
try
showmessage('ok');
except
ShowMessage('except');
end;
finally
ShowMessage('finally');
end
end;