如何防止我的 VB 应用程序崩溃

How can I prevent my VB application to crash

希望你能帮我解决我的问题。

我收到此错误:

System.Net.WebException:
The remote server returned an error: (401) Unauthorized.

当我点击 button_2 时。我想防止应用程序崩溃使用,显示 MessageBox 错误或类似的东西。
有人可以帮忙吗?

Private Sub Guna2Button1_Click(sender As Object, e As EventArgs) Handles Guna2Button1.Click
    Dim api As String
    api = Guna2TextBox1.Text
    Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("link")
    Dim wc As New WebClient
    Dim data As String
    Dim response As System.Net.HttpWebResponse
    Try
        response = request.GetResponse()
    Catch ex As System.Net.WebException
        MsgBox("Bad API")
    End Try
    MsgBox("Good API")

        data = wc.DownloadString("link")
        Dim IPV4Regex = New Regex("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
        Dim ipstr As String = ("")
        Dim total As String = ("")
        Dim myJObject = JObject.Parse(data)

        For Each match In myJObject("matches")
            Dim ip = match("http")("host")
            If IPV4Regex.Match(ip).Success Then
                ipstr = ip
                total = total + ipstr & vbCrLf
                Guna2TextBox2.Text = total
                Label4.Visible = True
            End If
        Next
End Sub

试试这个

Dim response As System.Net.HttpWebResponse

            Try
                response = request.GetResponse()
            'Put other lines here...
            Catch ex As System.Net.WebException
                msgbox("Something bad happened")
            End Try

如果 api 错误,为什么您的代码不会停止!! 您的代码必须在进入下一步之前处理任何错误 至少使用 Exit Sub

Try
    response = request.GetResponse()
Catch ex As System.Net.WebException
    MsgBox("Bad API")

    Exit Sub

End Try
MsgBox("Good API")