【问题标题】:Why doesn't Try/Catch work within number types?为什么 Try/Catch 在数字类型中不起作用?
【发布时间】:2013-10-10 19:45:54
【问题描述】:
Dim mynumber as Integer 'This is the variable as an integer, (Integers only allow WHOLE numbers)

Console.WriteLine("Enter your number..") 'Ask to enter number
    Try
        mynumber = Console.ReadLine 'Read user input and store it
    Catch
        Console.WriteLine()
        Console.ForegroundColor = ConsoleColor.Red
        Console.WriteLine("Only whole numbers allowed! Press enter to start again!")
        Console.ResetColor()
        Console.ReadLine()
        Console.Clear()
        GoTo start
    End Try

好的,大家可以从上面的示例中看到,我设置了一个 Try/Catch 用于错误处理。我遇到了一个问题。是的 Try/Catch 代码阻止输入字母(字符串),但是当我输入十进制数字时,它仍然接受它。为什么?如何防止这种情况发生?十进制数不应该被接受,因为整数只接受整数!

谢谢。

【问题讨论】:

  • 我认为上述案例是异常处理的一个不好的例子。 Try/Catch 块应该用于捕获 unexpected 错误。很明显,用户可以输入无效数据,所以这应该在IF...THEN 块中处理。还要确保在捕获异常时使用最具体的类型。 Catch ex As Exception 只会吃掉它遇到的任何错误。 Catch ex As InvalidCastException 会更好,它表明你知道预计会发生哪种错误。
  • @Neolisk,啊……这真的很复杂!

标签: vb.net try-catch


【解决方案1】:

数字类型之间存在隐式转换,因此不会触发错误。有不同的方法可以知道确切的数字类型。我想这里最好的选择是以下代码行:

Dim mynumber0 As Double 'This is the variable as an integer, (Integers only allow WHOLE numbers)
Dim wasOK As Boolean = True
Console.WriteLine("Enter your number..") 'Ask to enter number
Try
    mynumber0 = Console.ReadLine 'Read user input and store it
    If (Convert.ToInt32(mynumber0) <> mynumber0) Then
        wasOK = False
    End If
Catch
    wasOK = False
End Try

Dim mynumber As Integer = mynumber0
If (Not wasOK) Then
    Console.WriteLine()
    Console.ForegroundColor = ConsoleColor.Red
    Console.WriteLine("Only whole numbers allowed! Press enter to start again!")
    Console.ResetColor()
    Console.ReadLine()
    Console.Clear()
    GoTo start
End If

更新

TryParse 替代方案,由 mafafu 建议

Dim mynumber As Integer 'This is the variable as an integer, (Integers only allow WHOLE numbers)
Console.WriteLine("Enter your number..") 'Ask to enter number
If (Not Integer.TryParse(Console.ReadLine, mynumber)) Then
    Console.WriteLine()
    Console.ForegroundColor = ConsoleColor.Red
    Console.WriteLine("Only whole numbers allowed! Press enter to start again!")
    Console.ResetColor()
    Console.ReadLine()
    Console.Clear()
    GoTo start
End If

【讨论】:

  • 你也可以使用 Integer.TryParse() 如果输入有任何小数位则返回 false。
  • @mafafu,你能举个简单的例子吗?
  • @varocarbas,谢谢,似乎有很多代码用于一些小事。没有更快/更简单的方法吗?
  • @mafafu 谢谢。我会将其包含在我的答案中以说明所有选项。
  • 如果为假,Throw New Exception("Not an Integer!") 这样你就可以在没有布尔状态的情况下进入 catch 块。我的意思是,也许。无论哪种方式都有效。
【解决方案2】:

如前所述,您可以使用 Integer.TryParse 来检查是否可以将数字解析为整数。此外,您确实应该使用 Option Strict On,这将有助于 Visual Studio 指出 VB.NET 代码中的问题。

我对答案的看法:

Option Strict On

Module Module1

    Sub Main()

        Dim myNumber As Integer 'This is the variable as an integer, (Integers only allow WHOLE numbers)
        Dim userInput As String
        Dim userInputValid As Boolean = False

        While Not userInputValid
            Console.Write("Enter your number.. ") 'Ask to enter number

            userInput = Console.ReadLine() 'Read user input and store it
            userInputValid = Integer.TryParse(userInput, myNumber)
            If Not userInputValid Then
                Console.ForegroundColor = ConsoleColor.Red
                Console.WriteLine("Only whole numbers allowed! Press enter to start again!")
                Console.ResetColor()
                Console.ReadLine()
                Console.Clear()
            End If

        End While

        Console.WriteLine("I got the number " & myNumber.ToString())
        Console.ReadLine()

    End Sub

End Module

编辑:请参阅Option Strict Statement 上的“为新项目设置 Option Strict 默认设置”部分。

【讨论】:

    【解决方案3】:

    使用 Option Strict Off 时,VB.NET 试图表现得像旧版本的 VB,后者在类型检查方面有相当松散的规则。字符串、浮点类型和整数类型在很大程度上可以互换使用,并且尝试将浮点值分配给整数类型会以某种方式对其进行舍入(我忘记了确切的细节)。虽然有一些非常罕见的情况下 Option Strict Off 可以用于其他目的,而不是让旧的 VB6 代码有机会工作,但只有足够专业的人才能理解这种情况的复杂性,甚至应该考虑在所有情况下使用它任何新代码(即便如此,也仅限于可能有用的非常小的部分)。

    顺便提一下,如果将浮点值四舍五入到最接近的整数会产生一个值,那么即使 VB.NET 也认为从浮点值到整数类型的转换是“成功的”。即使浮点值具有在转换过程中被丢弃的非零小数部分,它也可以在该类型中表示。我不喜欢这种设计(我认为如果想要Int32 最接近给定的浮点值,应该使用这样的函数)但它就是这样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-18
      • 2017-06-12
      • 1970-01-01
      • 2015-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多