Delphi之Raise抛出异常

 

相关资料:

http://blog.csdn.net/a20071426/article/details/10160171

https://www.cnblogs.com/jijm123/p/11010309.html

 

实例代码:

 

 1 unit Unit1;
 2 
 3 interface
 4 
 5 uses
 6   Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 7   Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
 8 
 9 type
10   TMyException = class(Exception)
11     FMessage: string;
12     FInt: Integer;
13     FStr: string;
14     FBool: Boolean;
15     public
16     constructor Create(const Msg: string);
17     property Message: string read FMessage write FMessage;
18     property Int: Integer read FInt;
19     property Str: string read FStr;
20     property Bool: Boolean read FBool;
21   end;
22 
23   TForm1 = class(TForm)
24     Button1: TButton;
25     Button2: TButton;
26     Button3: TButton;
27     Button4: TButton;
28     procedure Button1Click(Sender: TObject);
29     procedure Button2Click(Sender: TObject);
30     procedure Button3Click(Sender: TObject);
31     procedure Button4Click(Sender: TObject);
32   private
33     { Private declarations }
34   public
35     { Public declarations }
36   end;
37 
38 var
39   Form1: TForm1;
40 
41 implementation
42 
43 {$R *.dfm}
44 
45 procedure TForm1.Button1Click(Sender: TObject);
46 var
47   Int1: Integer;
48 begin
49   try
50     Int1 := StrToInt('A');
51   except
52     raise Exception.CreateFmt('%d = %s',[1001, '您的程序在Unit1单元35行出错了!']);//1001=您的程序在Unit1单元35行出错了!
53   end;
54 end;
55 
56 { TMyException }
57 
58 constructor TMyException.Create(const Msg: string);
59 begin
60   FMessage := Msg;
61   FInt := 100;
62   FStr := 'NO';
63   FBool := False;
64 end;
65 
66 procedure TForm1.Button2Click(Sender: TObject);
67 begin
68   try
69     raise TMyException.Create('aaaaa');
70   except
71     on e:TMyException do
72     begin
73       ShowMessage(e.Message); //aaaaa
74       ShowMessage(IntToStr(e.Int)); //100
75       ShowMessage(e.Str); //NO
76       ShowMessage(BoolToStr(e.Bool)); //0
77     end;
78   end;
79 end;
80 
81 procedure TForm1.Button3Click(Sender: TObject);
82 begin
83   raise Exception.Create('抛出异常');   //抛出异常
84 end;
85 
86 procedure TForm1.Button4Click(Sender: TObject);
87 var
88   exc: Exception;
89 begin
90   exc := Exception.Create('发现异常'); //发现异常
91   raise exc;
92 end;
93 
94 end.

 

posted on 2017-01-13 09:34  疯狂delphi  阅读(475)  评论(0编辑  收藏  举报

导航