不,在您的示例中,如果Foo 抛出异常,则将立即进入Catch 块。 Boo 函数将不被调用,a 的值将不被设置。
即使您的 Main 函数没有使用任何 Try/Catch 块,这也是正确的:
Public Sub Main()
Dim a As Integer
If (Foo()) Then
a = Boo()
End If
End Sub
Boo() 只会被调用,a 只会被设置为其结果,如果Foo 不抛出异常。如果Foo 抛出,运行时将搜索合适的异常处理程序。找不到,而且这是顶级方法,您将遇到未处理的异常,然后导致应用程序终止。
这就是为什么不应该将异常用于流量控制,而只能用于实际的异常情况。
only 将您希望抛出的东西放入 Try 块中,only 将 Catch 块用于您知道如何处理的异常。我还建议尽可能在声明中初始化变量。一些虚构的代码作为逻辑上应该如何工作的示例:
Public Sub Main()
Dim val As Integer = 0 ' 0 is our "default" value
' Don't need a Try here, this won't throw an exception.
' It will just return an empty string if they canceled.
Dim fileName As String = AskUserForFileName()
' See if they canceled...
If (fileName <> String.Empty)
Try
' Now we need a Try block, because we're going to do
' stuff that might throw an exception.
Dim file As File = OpenFile(fileName)
' Execution won't get here if OpenFile() threw an exception, so
' at this point, we know that the file was opened successfully,
' so we'll try to read our value from it.
val = ReadDataFromFile(file)
' Again, execution won't get here if ReadDataFromFile() threw
' an exception, so we know that the data was read out successfully
' and our val variable has been updated.
Catch ex As FileNotFoundException
MessageBox.Show("Could not find the specified file.")
Catch ex As System.IO.IOException
MessageBox.Show("Could not read from the specified file--check it is valid.")
End Try
End If
' Our variable val will now contain the value read from the file,
' if that whole business was successful. Otherwise, it will
' contain the default value of 0 that we set at the top.
End Sub
在实际代码中,您还可以广泛使用Using blocks 来处理实现IDisposable 接口的任何对象的自动 清理,以防引发异常。修改我们上面的例子,假设我编写的File 类实现了IDisposable:
Public Sub Main()
Dim val As Integer = 0 ' 0 is our "default" value
' Don't need a Try here, this won't throw an exception.
' It will just return an empty string if they canceled.
Dim fileName As String = AskUserForFileName()
' See if they canceled...
If (fileName <> String.Empty)
Try
' Now we need a Try block, because we're going to do
' stuff that might throw an exception.
Using file As File = OpenFile(fileName)
' Execution won't get here if OpenFile() threw an exception, so
' at this point, we know that the file was opened successfully,
' so we'll try to read our value from it.
val = ReadDataFromFile(file)
' Again, execution won't get here if ReadDataFromFile() threw
' an exception, so we know that the data was read out successfully
' and our val variable has been updated.
End Using ' make sure file always gets closed properly
Catch ex As FileNotFoundException
MessageBox.Show("Could not find the specified file.")
Catch ex As System.IO.IOException
MessageBox.Show("Could not read from the specified file--check it is valid.")
End Try
End If
' Our variable val will now contain the value read from the file,
' if that whole business was successful. Otherwise, it will
' contain the default value of 0 that we set at the top.
End Sub