vb.net - VB.net逻辑可捕获函数错误

标签 vb.net function error-handling

我不是专业人士,我自己学习一些编码规则。
我从vba开始,现在我正在学习vb.net,但是我的知识很差。

我编写了此函数以从记录集(在DB上查询)提取列,并将其放入字符串的Hashset中。

为了处理错误的列数错误,我使用了以下标准:

1)在调用函数的代码中将“mErr”声明为boolean

2)发送“mErrbyRef到函数;

3)发生错误时:将mErr更改为true,然后在mHash中插入一个空字符串。

Public Function RSCol(ByVal mRS As Object, ByVal mCol As Byte, ByRef mErr As Boolean)
    Dim i As Long
    Dim mHash As New HashSet(Of String)
    If mRS.GetUpperBound(0) < mCol Then
        mErr = True
        mHash.Add("")
        Return mHash
        Exit Function
    End If
    For i = 0 To mRS.GetUpperBound(1)
        mHash.Add(mRS(mCol, i))
    Next
    Return mHash
End Function

它似乎可以工作,但是我认为这不是一个很好的编码,我想提高自己的编码技巧。

每个建议表示赞赏。

最佳答案

在您的代码中:

Exit Function is unreachable since the Return statement above the Exit Function function will transfer the control out to the function.

More over a function should return a value otherwise you will get a warning. in such cases you can use Sub.



您可以编码为
 Public Function RSCol(ByVal mRS As Object, ByVal mCol As Byte, ByRef mErr As Boolean) As HashSet(Of String)
        Dim loopCounter As Long
        Dim mHash As New HashSet(Of String)
        Try
            If mRS.GetUpperBound(0) < mCol Then
                Throw New Exception("")
            End If
            For loopCounter = 0 To mRS.GetUpperBound(1)
                mHash.Add(mRS(mCol, loopCounter))
            Next
        Catch ex As Exception
            mHash.Add(ex.ToString())
        End Try
        Return mHash
    End Function

您可以详细引用Try..Catch机制Click Here
有关Exceptions的更多信息

由于我注意到您的命名约定非常糟糕,因此建议您仔细阅读article by Microsoft

关于vb.net - VB.net逻辑可捕获函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30368779/

相关文章:

c++ - Boost.Spirit、Nabialek 技巧和错误处理

mysql - 将Access数据库表中的记录一一插入/复制到MySQL远程数据库

c++ - 调用 C/++ 函数时的观察和困惑

javascript - SIgmoid 函数的语法 - Javascript

python - 如何从 Python 3 的函数内更新全局变量?

php - 将PHP error_log文件保留在Web根目录之外

java - Spring Boot 自定义错误 Controller 返回空 JSON 响应

c# - 如何将多个选定的 Datagrid 值传递到 asp.net 中的另一个页面?

arrays - 将 VB.Net 数组转换为 C#

.net - Task.Wait 不等待