如何使用 Try、Catch 和 Finally

How do I use Try, Catch, and Finally

我的任务是编写一个程序,要求用户输入 10 个数字,然后计算这些数字的平均值,并且必须包含 Try、Catch 和 Finally 关键字。 (除以零例外)。

如何使用 Try、Catch 和 Finally?

到目前为止我的程序是这样的:

Module Module1
    Public Sub Main()
            Dim A, B, C, D, E, F, G, H, I, J, K, L, M As Integer
            Console.WriteLine("Enter 1st Number: ")
            A = Console.ReadLine()
            Console.WriteLine("Enter 2nd Number: ")
            B = Console.ReadLine()
            Console.WriteLine("Enter 3rd Number: ")
            C = Console.ReadLine()
            Console.WriteLine("Enter 4th Number: ")
            D = Console.ReadLine()
            Console.WriteLine("Enter 5th Number: ")
            E = Console.ReadLine()
            Console.WriteLine("Enter 6th Number: ")
            F = Console.ReadLine()
            Console.WriteLine("Enter 7th Number: ")
            G = Console.ReadLine()
            Console.WriteLine("Enter 8th Number: ")
            H = Console.ReadLine()
            Console.WriteLine("Enter 9th Number: ")
            I = Console.ReadLine()
            Console.WriteLine("Enter 10th Number: ")
            J = Console.ReadLine()
            K = (A+B+C+D+E+F+G+H+I+J)
            Console.WriteLine("Enter the amount of numbers to average: ")
            M = Console.ReadLine()
            L = K / M
            Console.WriteLine("The Average Is: " & L)
            Console.ReadKey()
    End Sub
End Module

TryCatchFinally 块对于处理在正常情况下会导致程序崩溃的错误非常有用。

例如:

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

您还可以获得有关确切错误的信息,一个可能的用途是您可能希望将其过滤掉,以便忽略特定错误,例如:

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

三部分:

  1. Try: 尝试执行此块内的代码,如果失败;

  2. Catch: Catch exception/error和执行 这个块里面的代码

  3. Finally: Finally 执行此块内的代码 regardless[= TryCatch 组件中发生的事情的 59=]。

例如,您可以针对您的特定用例使用类似这样的东西:

[...]
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

official documentation 有一些有用的信息。

正如对您的问题发表评论的用户所说(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 看到它们。您的代码也可以通过使用 For 循环和 ArrayList,但我会把它留给你去做。