我的任务是编写一个程序,询问用户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
Try,Catch,Finally块对于处理错误非常有用,在正常情况下它会导致程序崩溃.
例如:
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
这三部分:
>尝试:尝试执行此块中的代码,如果失败;
> Catch:捕获异常/错误并执行此块内的代码
>最后:最后在此块中执行代码,无论Try和Catch组件中发生了什么.
例如,您可以针对特定用例使用类似的内容:
[...] 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循环和数组或列表,您的代码也可以更高效,但我会留给您做.