我怎么能抓住呢? DEF'异常(例如:负双数的Sqrt)

时间:2015-08-11 14:25:21

标签: .net vb.net visual-studio-2013 exception-handling sqrt

Dim number As Double = 0
Dim result As Double = 0

number = -10
Try
    result = Math.Sqrt(number)

Catch ex As Exception
    MsgBox("ex = " & ex.ToString)
End Try

MsgBox("result = " & result)

运行此代码段时,我得到:result = n. def而不是捕获异常。

2 个答案:

答案 0 :(得分:1)

如果输入值为负as detailed here

Math.Sqrt不会抛出异常

但你可以在sqrt之后检查该值是否有效,如果不是

则抛出你自己的异常 如果值为“Not a Number”,则

Double.IsNaN会返回True

    Dim number As Double = 0
    Dim result As Double = 0
    number = -10
    Try
        result = Math.Sqrt(number)
        If Double.IsNaN(result) Then Throw New Exception("Square root cannot be calculated for the value " & number)
    Catch ex As Exception
        MsgBox("ex = " & ex.ToString)
    End Try

    MsgBox("result = " & result)

请注意,即使抛出异常,您仍然会显示第二个消息框,因此我建议这样的事情可能更好:

    Dim number As Double = 0
    Dim result As Double = 0
    number = -10
    Try
        result = Math.Sqrt(number)
        If Double.IsNaN(result) Then
            MsgBox("ex = " & "Square root cannot be calculated for the value " & number)
        Else
            MsgBox("result = " & result)
        End If

    Catch ex As Exception
        MsgBox("ex = " & ex.ToString)
    End Try

答案 1 :(得分:1)

您的代码工作正常,因为没有例外可以捕获。

MSDN documentation中所述,Math.Sqrt在传递负参数时返回Double.NaN;它会抛出任何异常。

当前文化为德语(“de-DE”)时,

Double.NaN.ToString()将返回n. def.