本例演示了全局的异常捕获及处理, 并模拟激发了一个异常; 编译后, 单独运行一下生成的程序文件...
本例效果图:
代码文件:
unit Unit1;
interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
procedure
AppException(Sender: TObject; E: Exception);
end;
var Form1: TForm1;
implementation
{$R *.dfm}
type
MyException = Class(Exception);
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.OnException := AppException;
Button1.Caption := '激发一个异常';
end;
procedure TForm1.AppException(Sender: TObject; E: Exception);
begin Application.ShowException(E);
Application.Terminate;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
raise MyException.Create('发生异常, 将要退出!');
end;
end.