学习官方示例 - TApplication.OnException

本例演示了全局的异常捕获及处理, 并模拟激发了一个异常; 编译后, 单独运行一下生成的程序文件...
本例效果图:

学习官方示例 - TApplication.OnException_第1张图片
代码文件:
unit Unit1;

interface

uses
  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.

 
 
 
 
 

 

 
  
窗体文件:
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 151
  ClientWidth = 258
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesktopCenter
  OnCreate = FormCreate
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
    Left = 80
    Top = 64
    Width = 97
    Height = 25
    Caption = 'Button1'
    TabOrder = 0
    OnClick = Button1Click
  end
end

 
 
 
 
 

 

 
  

你可能感兴趣的:(学习官方示例 - TApplication.OnException)