您的位置:首页 > 其它

简单的.net 中的异常处理

2006-09-12 17:17 477 查看
工作线程中的异常处理(利用me.BeginInvoke 异步调用委托)

1 '异常处理的委托
2 Public Delegate Sub threadWorkerException(ByVal e As Exception)
3
4 '这里可以换成你要处理的具体行为
5 Sub threadExceptionHandle(ByVal e As Exception)
6 Me.Label1.Text = "出现了异常" & e.Message & " " & e.GetType.ToString
7 End Sub
8
9 '开始一个Thread, 进行处理
10 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
11 ' start a threading
12 Dim aThread As New Thread(AddressOf ThreadingSub)
13 aThread.Start()
14 End Sub
15
16 ' 线程的具体操作,在里面人为的产生一个Excepion
17 Dim i As Integer = 10
18 Dim j As Integer
19 Try
20 j = Integer.Parse(Me.TextBox1.Text)
21 Debug.WriteLine(i / j)
22 Me.Label1.Text = "success"
23 Catch ex As Exception
24 Me.Invoke(New threadWorkerException(AddressOf threadExceptionHandle), New Object() {ex})
25 End Try
26
27

2 使用Application对象中的ThreadException属性可以设置一个delegate来捕获所有未处理的Main UI线呈中出现的异常

1 Public Sub New()
2 MyBase.New()
3 'This call is required by the Windows Form Designer.
4 InitializeComponent()
5 '增加全局Exception的处理
6 AddHandler Application.ThreadException, New System.Threading.ThreadExceptionEventHandler(AddressOf GlobalExceptionHandle)
7 End Sub
8
9 '全局异常处理函数的细节,在这里你可以、增加自己的处理逻辑
10 Public Sub GlobalExceptionHandle(ByVal sender As Object, ByVal e As System.Threading.ThreadExceptionEventArgs)
11 MsgBox(e.Exception.Message)
12 End Sub
13
14 '人为的产生一个异常
15 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
16 Dim i As Integer = 10
17 Dim j As Integer = Integer.Parse(Me.TextBox1.Text)
18 MsgBox(i / j)
19 End Sub
20
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: