Delphi的学习笔记十七——Exception处理

异常常用在硬件、内存、I/O和操作系统错误中。

[delphi]  view plain  copy
  1. try  
  2.    AssignFile(F,FileName);  
  3.    Reset(F);  
  4. except  
  5.    on Exception do ...  
  6. end;  

定义并声明一个异常:

[delphi]  view plain  copy
  1. function StrToIntRange(const S:string;Min,Max: Longint) : Longint;  
  2. begin  
  3.     Result := StrToInt(S);  
  4.     if (Result < Min) or (Result > Max) then  
  5.    raise ERangeError.CreateFmt('%d is not within the valid range of %d..%d',[Result,Min,Max]);  
  6. end;  

语法:

[delphi]  view plain  copy
  1. try  
  2.   X := Y/Z;  
  3. except  
  4.   on EZeroDivide do HandleZeroDivide;  
  5. end;  

[delphi]  view plain  copy
  1. try  
  2. ...  
  3. except  
  4.   on EZeroDivide do HandleZeroDivide;  
  5.   on EOverflow do HandleOverflow;  
  6.   on EMathError do HandleMathError;  
  7. else  
  8.   HandleAllOther;  
  9. end;  


Re-raising exception(重新引发一个异常)

[delphi]  view plain  copy
  1. function GetFileList(const Path: string): TStringList;  
  2. var  
  3.    I: Integer;  
  4.    SearchRec: TSearchRec;  
  5. begin  
  6.    Result := TStringList.Create;  
  7.    try  
  8.       I:= FindFirst(Path,0,SearchList);  
  9.      While I = 0 do  
  10.      begin  
  11.          Result.Add(SearchRec.Name);  
  12.          I := FindNext(SearchRec);  
  13.      end;  
  14.    except  
  15.      Result.Free;  
  16.      raise;  
  17.    end;  
  18. end;  

 

Nested Exception(内嵌异常)

[delphi]  view plain  copy
  1. type  
  2.   ETrigError = class(EMathError);  
  3. function Tan(X : Extended) : Extended;  
  4. begin  
  5.     try  
  6.       Result := Sin(X) /Cos(X);  
  7.     except  
  8.       on EMathError do  
  9.           raise ETrigError.Create('Invalid argument to Tan');  
  10.    end;  
  11. end;  

try……finally

[delphi]  view plain  copy
  1. Reset(F);  
  2. try  
  3. ...  //process file F  
  4. finally  
  5.    CloseFile(F);  
  6. end;  

经常在开发中用到的是以下这种模式即try...except...finally

[delphi]  view plain  copy
  1. procedure TForm1.Button1Click(Sender: TObject);  
  2. begin  
  3.  try  
  4.    try  
  5.       showmessage('ok');  
  6.     except  
  7.        ShowMessage('except');  
  8.     end;  
  9.   finally  
  10.     ShowMessage('finally');  
  11.   end  
  12. end;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值