胖在一方

出得厅堂入得厨房的胖子

导航

简单的.net 中的异常处理

Posted on 2006-09-12 17:17  胖在一方  阅读(273)  评论(0)    收藏  举报
 工作线程中的异常处理(利用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 ObjectByVal 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