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   疯狂delphi  阅读(481)  评论(0)    收藏  举报

编辑推荐:
· 长文讲解 MCP 和案例实战
· Hangfire Redis 实现秒级定时任务,使用 CQRS 实现动态执行代码
· Android编译时动态插入代码原理与实践
· 解锁.NET 9性能优化黑科技:从内存管理到Web性能的最全指南
· 通过一个DEMO理解MCP(模型上下文协议)的生命周期
阅读排行:
· 工良出品 | 长文讲解 MCP 和案例实战
· 多年后再做Web开发,AI帮大忙
· centos停服,迁移centos7.3系统到新搭建的openEuler
· 记一次 .NET某旅行社酒店管理系统 卡死分析
· 上周热点回顾(4.14-4.20)

导航

统计

点击右上角即可分享
微信分享提示