Hi group! I hope all is well!

As part of my connection string and database insert/update, I have an exception command in it to display an error message. Can this also be read or made into a true/false answer?

I would like to have my program run very short command if the insert/update should fail. I'm thinking the best way to do this may be asking if the "Catch ex As Exception" is "True Then" run my short command. Can something like this be done? Or is there a better way to do this?

In advance, thanks for the help!

Don

Rev. Jim, let me try to be more specific:

I've created a 'Private Sub' that clears out the variable and textboxes one after the data is moved to the database. However, in the event that the command string fails (which is what it is doing right now), I want to put a "If/Then" statement in that will stop that sub-routine from running..... or better put, if it works, run the routine. If not, don't run it.

In thinking out loud about this, would this work correctly if I wrote the routine this way:

cmd.ExecuteNonQuery()
            Catch ex As Exception
                MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
            Finally
                con.Close()
                Call ClearFieldsAndVariables()  'This to run if the data is moved to the database
            End Try

Hopefully this explains it better.

Thoughts?

Thanks for you interest. I appreciate the help. Watch for another post I'm about to make about a connections string. The one I'm using doesn't always work. I'm not sure why. So I'll be looking for a "failsafe" command.

Don

Then what you want is

Try
    whatever command you run to do the insert
    Call ClearFieldsAndVariables()
Catch ex As Exception
    MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
    con.Close()
End Try

What happens is if the insert fails the Catch block is immediately executed. If the insert succeeds then the statements following that (in the Try block) get executed. The Finally portion gets executed whether an error occurs or not.

Rev. Jim,

If I understand you correctly, you're saying that, if the insert fails, nothing will be executed.... even the "Call ClearFieldsAndVariables" as the program will immediately jump to the "Catch ex As Exception".

Am I understanding you correctly?

As always, thanks!

Don

That is correct. When an error occurs in any line in the Try block, execution immediately transfers to the Catch block.

This question has already been answered. Start a new discussion instead.