【问题标题】:Is a return statement necessary for try catchtry catch 是否需要返回语句
【发布时间】:2014-03-10 17:50:39
【问题描述】:

我在一些电子邮件发送逻辑周围放置了一个 try/catch 块。如果邮件成功,它会给出一个确认信息,如果它失败,它会给出一个失败信息。 Visual Studio 警告我该函数不会在所有代码路径上返回值。我是否需要在每个 Try 和 Catch 块中放置 return 语句?如果我这样做了,例如将 False 或 Null 的 Return 语句放在 Try 和 Catch 的末尾,那么 Return 语句之前的其他代码还会执行吗?

Function Sendmail(ByVal subject As String, ByVal msg As String, ByVal fromAddress As String, ByVal toAddress As String)            
Try
                Dim message As New MailMessage
                message.From = New MailAddress(fromAddress)
                For Each s As String In toAddress.Split(New [Char]() {";"c})
                    message.To.Add(New MailAddress(s))
                Next
                message.Subject = subject
                message.Body = msg
                message.IsBodyHtml = False
                Dim client As New SmtpClient
                client.Send(message)
                pnlEmailSuccess.Visible = True
            Catch ex As Exception
                pnlEmailSuccess.Visible = False
                pnlEmailError.Visible = True
                lblErrorMsg.Text = ex.ToString
            End Try
End Function

【问题讨论】:

  • 如果您不需要返回值,请将其更改为 Sub 而不是 Function
  • 你可以将返回添加到最后,所以它会一直运行(如果你需要返回)

标签: vb.net return try-catch


【解决方案1】:

要回答您的问题,不,您不需要在 Try/Catch 中使用 return 语句。如果您不返回值,则不需要将其写入函数。您可以将其写在sub 语句或sub 过程中,而不是将其写在函数中。这里是link 了解更多关于sub 程序的信息。

【讨论】:

    【解决方案2】:

    VB.NET 期望函数中执行的最后一条语句是一个返回值,它将一个值发送回调用过程。当代码遇到 Return 语句时,它会立即终止代码的执行并返回指定的值,这就是为什么它通常是函数中的最后一条语句(参见下面的示例)。 VB.NET 只是警告您,该函数可能不会返回值(在您的情况下,这是肯定的,因为该函数只有一个退出点)。作为可能发生这种情况的另一个示例,请考虑一个具有两条不同路径的函数,代码可以通过这些路径退出:

    Function IsThisFive(ByVal x as Integer) as Boolean
        If x = 5 Then
            Return True 'One code path exits here, with return value
        Else
            MsgBox("This is not five!")
        End If
        ' Other code path exits here if x <> 5 -- no return value specified
    End Function
    

    那么要回答您的问题,不,您不需要在 Try 和 Catch 块中都有返回值。但是,您确实需要在 End Try 之后和 End Function 之前在块的末尾使用一个。代码将运行 Try..Catch..End Try 构造,然后返回一个值。

    如果你不需要它来返回一个值,为什么不把它变成一个 sub 而不是一个函数呢? sub 不应该返回一个值,从而消除了这个问题。 :-)

    如果您仍然希望它是一个函数,编程中的一个常见约定是只有一个子例程或函数的退出点。这使得在调试或读取代码时更容易遵循程序流程。

    你可以这样做:

    Function SendMail(ByVal subject As String, ByVal msg As String, ByVal fromAddress As String, ByVal toAddress As String) as Boolean
        Dim maiLSent as Boolean = False
        Try
            'send mail code
            mailSent = True
        Catch
            'exception handling code here
            mailSent = False
        End Try
    
        Return mailSent ' Only exit point from function is here
    End Function
    

    【讨论】:

      【解决方案3】:

      我使用 Try-Catch 将其添加到计时器中,而不是连续运行。完美运行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-14
        • 2014-03-10
        • 2018-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-25
        • 2021-12-25
        相关资源
        最近更新 更多