2015-12-31 52 views
0

我是Visual Basic的新手,尝试执行try和catch块的下面的代码。我只是检查一下,我们是否可以在VB.net中同时捕获多个异常。但我只得到一条消息。请清楚地解释我。我们可以在VB.net中同时捕获多个异常吗?

的代码是在这里下

Public Class tempIsZeroException : Inherits System.Exception 
    Public Sub New(ByVal mesage As String) 
     MyBase.New(mesage) 
    End Sub 
End Class 

Module Module1 

    Sub Main() 
     Dim a As Integer 
     Dim b As Integer 
     Console.WriteLine("ENter any number") 
     a = Console.ReadLine() 
     Console.WriteLine("ENter any number") 
     b = Console.ReadLine() 
     Try 

      If a = 0 Then 
       Throw New ApplicationException("asdf") 
      End If 
      If b = 0 Then 
       Throw New tempIsZeroException("Exception caught") 
      End If 
     Catch ex As TempIsZeroException 
      Console.WriteLine(ex.Message()) 
     Catch ex1 As ApplicationException 
      Console.WriteLine(ex1.Message()) 
     End Try 
     Console.ReadLine() 
    End Sub 

End Module 
+0

当你抛出一个异常时,代码跳转到相关的catch块,执行catch块中存在的任何代码,然后在End Try外面跳转。目前还不清楚你会从这段代码中得到什么结果...... – Steve

回答

1

可以赶上try块多的例外,但例外没有得到同步提高(至少在你的代码已经公布)。

换句话说,第一个引发的异常是第一个被捕获的异常。

在你的代码

所以,如果a = 0然后ApplicationException会被抓住而如果b = 0然后tempIsZeroException会被抓住,如果两个ab是等于0然后ApplicationException将引发异常,因为If a = 0块将首先被击中并抛出异常并绕过If b = 0块。

希望能够增加一些清晰度。

+0

非常感谢@txtechhelp –

相关问题