先来看看网友 zyjq52uys 在《vb.net 教程 2-11 错误处理》询问的一段代码:
Public Class Form1 Private Sub Button1_Click(sender As Object,e As EventArgs) Handles Button1.Click Dim f As Integer Try f = a(5,0) f = a(10,2) Catch End Try End Sub End Class Public Module mod1 Public Function a(ByVal c As Integer,ByVal d As Integer) Dim b As Integer Try b = c \ d Finally b = 0 End Try Return b End Function End Module
可以在f=a(5,0)处设置断点看看到底怎么运行的:
运行程序,按下按钮会进入调试:
(1)f=a(5,0) 进入方法a()
(2)定义b
(3)b=c\d ,不能除以0,产生错误
(4)设置了finally,但是没有处理错误
(5)返回b=0,但是错误没有处理
(7)由于有错误,直接调到了Catch语句,没有处理(6)
Public Class Form1 Private Sub Button1_Click(sender As Object,2) Catch ex As Exception 'MessageBox.Show(ex.Message) End Try MessageBox.Show(f) End Sub End Class Public Module mod1 Public Function a(ByVal c As Integer,ByVal d As Integer) Dim b As Integer Try b = c \ d Catch ex As Exception 'MessageBox.Show(ex.Message) Finally b = 0 End Try Return b End Function End Module
再看看运行情况:
(1)->(A)->除以0产生错误->(B)->由于有Finally->(C)->(D)->返回0->(2)->(A)->(C)->(D)->返回0->(5)
由于用了Catch处理了错误,所以不会经过(3)(4)
同时由于方法a()中调用Finally,所以每次返回b都为0,再次修改后的代码:
Public Class Form1 Private Sub Button1_Click(sender As Object,ByVal d As Integer) Dim b As Integer Try b = c \ d Catch ex As Exception b = 0 'MessageBox.Show(ex.Message) Finally '不处理 End Try Return b End Function End Module
运行后就会得到结果5
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看vb.net 教程 目录