我如何使用Try,Catch和Finally

时间:2015-01-09 22:56:45

标签: vb.net

我的任务是编写一个程序,询问用户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

1 个答案:

答案 0 :(得分:2)

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 异常/错误,执行此块内的代码

    < / LI>
  3. Finally 最后 执行此块中的代码,无论 Try中发生了什么和Catch组件。

  4. 例如,您可以针对特定用例使用类似的内容:

    [...]
    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),您的代码存在其他问题(不会覆盖它们,因为它超出了问题的范围)而您应该turn on Option Strict来看待他们。使用For循环和ArrayList,您的代码也可以提高效率,但我会留给您做。