Except1F.pas
上传用户:fh681027
上传日期:2022-07-23
资源大小:1959k
文件大小:2k
源码类别:

Delphi控件源码

开发平台:

Delphi

  1. unit Except1F;
  2. interface
  3. uses SysUtils, Windows, Messages, Classes, Graphics, Controls,
  4.   Forms, Dialogs, StdCtrls;
  5. type
  6.   TForm1 = class(TForm)
  7.     ButtonDivide1: TButton;
  8.     ButtonDivide2: TButton;
  9.     ButtonRaise1: TButton;
  10.     ButtonRaise2: TButton;
  11.     Label1: TLabel;
  12.     Label2: TLabel;
  13.     procedure ButtonDivide1Click(Sender: TObject);
  14.     procedure ButtonDivide2Click(Sender: TObject);
  15.     procedure ButtonRaise1Click(Sender: TObject);
  16.     procedure ButtonRaise2Click(Sender: TObject);
  17.   private
  18.     { Private declarations }
  19.   public
  20.     { Public declarations }
  21.   end;
  22. var
  23.   Form1: TForm1;
  24. implementation
  25. {$R *.DFM}
  26. {new type of exception}
  27. type
  28.   EArrayFull = class (Exception);
  29. function DivideTwicePlusOne (A, B: Integer): Integer;
  30. begin
  31.   try
  32.     // error if B equals 0
  33.     Result := A div B;
  34.     // do something else... skip if exception is raised
  35.     Result := Result div B;
  36.     Result := Result + 1;
  37.   except
  38.     on EDivByZero do
  39.     begin
  40.       Result := 0;
  41.       MessageDlg ('Divide by zero corrected',
  42.         mtError, [mbOK], 0);
  43.     end;
  44.     on E: Exception do
  45.     begin
  46.       Result := 0;
  47.       MessageDlg (E.Message,
  48.         mtError, [mbOK], 0);
  49.     end;
  50.   end; // end except
  51. end;
  52. {fake procedure: the array is always full}
  53. procedure AddToArray (N: Integer);
  54. begin
  55.   raise EArrayFull.Create ('Array full');
  56. end;
  57. procedure TForm1.ButtonDivide1Click(Sender: TObject);
  58. begin
  59.   DivideTwicePlusOne (10, 0);
  60. end;
  61. procedure TForm1.ButtonDivide2Click(Sender: TObject);
  62. var
  63.   A, B, C: Integer;
  64. begin
  65.   A := 10;
  66.   B := 0;
  67.   {generates an exception, which is not handled by us}
  68.   C := A div B;
  69.   {we have to use the result, or the optimizer will
  70.   remove the code and the error, too}
  71.   Caption := IntToStr (C);
  72. end;
  73. procedure TForm1.ButtonRaise1Click(Sender: TObject);
  74. begin
  75.   try
  76.     {this procedure raises an exception}
  77.     AddToArray (24);
  78.   except
  79.     {simply ignores the exception}
  80.     on EArrayFull do; {do nothing}
  81.   end;
  82. end;
  83. procedure TForm1.ButtonRaise2Click(Sender: TObject);
  84. begin
  85.   {unguarded call}
  86.   AddToArray (24);
  87. end;
  88. end.