


























1
using System;
2
using System.Drawing;
3
using System.Collections;
4
using System.ComponentModel;
5
using System.Windows.Forms;
6
using System.Data;
7
using System.Threading;
8
9
namespace Exception
10
{
11
/// <summary>
12
/// 异常处理。
13
/// </summary>
14
public class Form1 : System.Windows.Forms.Form
15
{
16
private System.Windows.Forms.Button button1;
17
private System.Windows.Forms.Button button2;
18
private System.Windows.Forms.Button button3;
19
/// <summary>
20
/// 必需的设计器变量。
21
/// </summary>
22
private System.ComponentModel.Container components = null;
23
24
public Form1()
25
{
26
//
27
// Windows 窗体设计器支持所必需的
28
//
29
InitializeComponent();
30
31
//
32
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
33
//
34
}
35
36
/// <summary>
37
/// 清理所有正在使用的资源。
38
/// </summary>
39
protected override void Dispose( bool disposing )
40
{
41
if( disposing )
42
{
43
if (components != null)
44
{
45
components.Dispose();
46
}
47
}
48
base.Dispose( disposing );
49
}
50
51
Windows Form Designer generated code
109
110
/// <summary>
111
/// 应用程序的主入口点。
112
/// </summary>
113
[STAThread]
114
static void Main()
115
{
116
Application.Run(new Form1());
117
}
118
class MyException:ApplicationException
119
{
120
public MyException(String msg):base(msg)
121
{
122
HelpLink = "http://NotARealURL.Microsoft.com/help.html";
123
}
124
}
125
public void ShowException(System.Exception ex)
126
{
127
string str;
128
str = string.Format("Exception:\n\t{0}\n", ex.GetType().ToString());
129
str += string.Format("Message:\n\t{0}\n", ex.Message);
130
str += string.Format("Stack Trace:\n\t{0}\n", ex.StackTrace);
131
str += string.Format("Help Link:\n\t{0}\n", ex.HelpLink);
132
MessageBox.Show(str);
133
}
134
// 除以 0 异常。
135
private void button1_Click(object sender, System.EventArgs e)
136
{
137
int x = 0;
138
try
139
{
140
// 产生异常。
141
x = 10 / x;
142
}
143
catch(System.Exception ex)
144
{
145
ShowException(ex);
146
}
147
}
148
// 无效对象异常。
149
private void button2_Click(object sender, System.EventArgs e)
150
{
151
object a = null;
152
try
153
{
154
MessageBox.Show(a.ToString());
155
}
156
catch(System.Exception ex)
157
{
158
ShowException(ex);
159
}
160
}
161
// 自定义异常。
162
private void button3_Click(object sender, System.EventArgs e)
163
{
164
try
165
{
166
throw(new MyException("这是我自己定义的异常。"));
167
}
168
catch(System.Exception ex)
169
{
170
ShowException(ex);
171
}
172
}
173
}
174
}
175
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。