简体   繁体   中英

Visual Basic (vb.net) How to check if task could not be completed

I was trying to make it so when my button is clicked, it will run through a series of tasks or things to do, but i want it so when if it fails to do anything of those tasks it will (do something) - Like Use MsgBox("This Operation Could Not Be Completed...")

Here Is My Button Code:

Private Sub SelectBtn_Click(sender As Object, e As EventArgs) Handles SelectBtn.Click
    Dim res = client.Get("Logins/" + usernamebox.Text)
    Dim std As New Student()
    std = res.ResultAs(Of Student)
    If std.Password = passwordbox.Text Then
        MsgBox("Welcome Back! " + usernamebox.Text + "!")
    Else
        MsgBox("Username OR Password May Be Wrong", MsgBoxStyle.Exclamation, "Login Error")
    End If

End Sub
    

Okay So This Is My Buttons Code, Its Getting Data From Firebase.. But I Want It So When It Fails It Will Not Break The Program.. And Instead It Displays A Message... The Reason Why I Want This Is For Some Reason The Program Breaks When A Value Doesnt "Exist" It Breaks And I Just Want A Message To Display If It Tries To Break And It To Carry On To Click It Again Etc.. Sorry For The Way I Type Im So Used To Visual Studio 2019... The Formatting Of Things Really Messed Me Up...

EDIT: 这就是我在使用 Try 块时得到的结果

You will need to use a Try/Catch block: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/try-catch-finally-statement

In your case, it may look something like this:

Try
    Dim res = client.Get("Logins/" + usernamebox.Text)
    Dim std As New Student()
    std = res.ResultAs(Of Student)

    ' student is null, login failed
    If (std Is Nothing) Then
        MessageBox("Username OR Password May Be Wrong", MsgBoxStyle.Exclamation, "Login Error")
    End If

    If (std.Password = passwordbox.Text) Then
        MessageBox("Welcome Back! " + usernamebox.Text + "!")
    Else
        ' student is not null, but the password doesn't match
        MessageBox("Username OR Password May Be Wrong", MsgBoxStyle.Exclamation, "Login Error")
    End If
Catch ex As Exception
    MessageBox.Show("This operation could not be completed.")
    Console.WriteLine(ex.Message) ' see what cause the exception in the output dialog
End Try

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM