0

我创建了一个包含三个输入文本框的学生课程注册表格:

  • 名和姓
  • 电话号码
  • 地址

然后我有另一个文本框,用于显示学生信息。我将此仅显示的文本框称为“课程”文本框。

我想在这个表单上使用结构化异常处理(Try/ Catchblock)。我怎么能在这种表格上做到这一点。

4

2 回答 2

4

使用 Try/Catch 处理异常

VB.Net 中的异常处理非常简单。以下代码是 try/catch 块的结构。

 Try
       'This is the code you wish to try that  might give an error.
    Catch ex As Exception
       'This is where you end up if an error occurs.
    End Try

假设您的表单上有一个按钮,并且您想确保在按下按钮后,您拥有的所有指令都将得到正确处理。下面的代码说明了。首先放下一个按钮并将其命名为ValidationButton。如果你双击你的新按钮,在后面的代码中你会看到一个处理点击事件的新函数。如下所示,将 try catch 块添加到其中。

Private Sub ValidationButton_Click(sender As System.Object, e As System.EventArgs) Handles ValidationButton.Click
    Try

    Catch ex As Exception

    End Try
End Sub

现在页面有一个按钮,其中的代码位于 try/catch 块中。我们只需将我们想要的代码放入其中。让我们放一些会抛出错误的东西,然后我们将显示该错误。

示例代码

Private Sub ValidationButton_Click(sender As System.Object, e As System.EventArgs) Handles ValidationButton.Click
    Try
        Dim x As Integer = 1
        Dim y As Integer = 0
        Dim z As Integer = x / y
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

弹出一个消息框,告诉我们遇到错误,“算术运算导致溢出”。这当然是因为我们不能除以零。如果你没有把它放在 try catch 中,程序就会崩溃。

所以,有了这些信息,把你的 try/catch 放在你可能出错的地方。如果您知道您的错误可能是什么,您甚至可以在其中编写代码来执行其他操作。在我们的示例中,我们可能想告诉用户不要除以零。

于 2013-02-19T15:08:17.827 回答
2

除了捕获特定代码行中的错误之外,您还可以捕获未处理的错误。最简单的方法是通过主程序启动应用程序

Module Program

    Public Shared Sub Main()
        AddHandler Application.ThreadException, AddressOf UIThreadException

        ' Force all Windows Forms errors to go through our handler.
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)

        ' Start the main Form
        Application.Run(New frmMain())
    End Sub

    Private Shared Sub UIThreadException(ByVal sender As Object, _
                                         ByVal t As ThreadExceptionEventArgs)
        ' Handle the error here
    End Sub

End Module

您可以在 MSDN 上阅读有关此主题的更多信息:Application.ThreadException 事件

于 2013-02-19T15:36:53.797 回答