A Try
, Catch
, Finally
block is extremely useful for handling errors where in a normal instance it would cause the program to crash.
For example:
Dim n As Integer
Dim a As Integer = 0
Dim b As Integer = 1
Try
n = b / a
Catch
MsgBox("We've crashed :(")
Finally
MsgBox("..but we're still alive!")
End Try
You are also able to get the information on the exact error, a possible use of this is that you might want to filter it out so specific errors are ignored, like per se:
Dim n As Integer
Dim a As Integer = 0
Dim b As Integer = 1
Try
n = a / b
Catch ex As DivideByZeroException
MsgBox("We've crashed, here's the specific error: " + ex.Message)
Catch ex As Exception
MsgBox("Some other error happened: " + ex.Message)
Finally
MsgBox("..but we're still alive!")
End Try
The three parts:
Try
: Try executing the code within this block, if it fails;
Catch
: Catch the exception/error and execute the code inside this block
Finally
: Finally execute code inside this block regardless of what happened in the Try
and Catch
components.
For example you could use something like this for your specific use case:
[...]
Try
L = K / M
Console.WriteLine("The Average Is: " & L)
Console.ReadKey()
Catch
Console.WriteLine("Uh oh, we've divided by 0!")
Finally
Console.WriteLine("Press any key to continue.")
[...]
End Try
The official documentation has some handy information.
As a user who commented on your question said (Mark), there's other issues with your code (not covering them because it'll go outside the scope of the question) and you should turn on Option Strict
to see them. Your code could also be made more efficient by utilising a For
loop and an Array
or List
, but I'll leave that to you to do.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…