【问题标题】:Exit parent Sub退出父子
【发布时间】:2014-03-17 07:42:58
【问题描述】:

我有点困惑如何处理我正在编写的 VB .net 应用程序中的错误。

这就是我所拥有的:

Private Sub Func1()
 Try
   'stuff that could raise an error

 Catch ex As Exception
   MsgBox("There is an error" & ex)
   End
 End Try

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  Func1()
 'a lot of stuff that will also raise an error is Func1 does
End Sub

如果出现错误,此代码将退出应用程序。

如果我删除“结束”,它将继续并在 Sub Button1_click 中引发多个错误。

所以我需要在 Func1 中添加一些可能会中断 Sub Button1_click 执行的内容。

我可以设置 Exit Sub,但我有很多使用此 Func1 的 Sub,所以我更喜欢从 Func1 中执行此操作的方法。

【问题讨论】:

    标签: vb.net error-handling


    【解决方案1】:

    如果您不想在 Func1 失败时继续执行 Button1_Click,则将 Func1 更改为布尔函数

    Private Function Func1() As Boolean
     Try
       'stuff that could raise an error
    
       Return True
     Catch ex As Exception
       MsgBox("There is an error" & ex)
       return False
     End Try
    
    End Function
    
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      if Func1() = True Then
         'a lot of stuff that will also raise an error is Func1 does
      End If
    End Sub
    

    【讨论】:

      【解决方案2】:

      如果您只想向用户显示文本,请不要在如此低的级别捕获异常。

      Application.ThreadException 和/或AppDomain.UnhandledException 事件中安装一个处理程序并在那里调用MsgBox

      如果你这样做了,Try/Catch 块在Func1 中根本不需要,如果发生异常,Func1Button1_Click 的其余部分不会运行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-21
        • 1970-01-01
        • 2013-08-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-28
        • 2016-07-01
        • 1970-01-01
        相关资源
        最近更新 更多