0

我在 VB.NET 中有一个方法,它只是抛出异常的助手。它总是会抛出异常并且永远不会返回但是编译器不会将此函数检测为终止代码路径,因此如果我稍后在代码中使用未通过异常代码路径初始化的变量,我会收到警告。

Function Foo(y as Integer) As Boolean
    dim x as boolean
    if y > 10
        x = 20
    else
        ThrowHelperFunction("Ouch")
    end if
    return x
End Function

警告是 x 未在所有代码路径上初始化。

4

3 回答 3

3

我不认为你可以改变这种行为。相反,您可以执行以下操作:

Function Foo(y as Integer) As Boolean
    dim x as boolean
    if y > 10
        x = 20
    else
        throw CreateExceptionHelperFunction("Ouch")
    end if
    return x
End Function

也就是说,辅助函数仍然可以做一些处理。但它会返回一个异常而不是抛出它。

于 2012-09-07T08:04:12.550 回答
1

尝试使用像这样的一些默认值来初始化 x 。Boolean 是值类型,不应该用空值初始化。

Function Foo(y as Integer) As Boolean     
    dim x as boolean     
    x = 0
    if y > 10         
        x = 20     
    else         
        throw CreateExceptionHelperFunction("Ouch")     
    end if     
    return x 
End Function 
于 2012-09-07T08:19:39.323 回答
0

尝试使用以下代码(使用 Sub 而不是 Function)

Sub Foo(y As Integer)
    Dim x As Boolean
    If y > 10 Then
        x = 20
    Else
        ThrowHelperFunction("Ouch")
    End If
End Sub

谢谢。

于 2012-09-07T08:17:28.147 回答