views:

158

answers:

1

Hi all,

I'm using Visual Studio 2008 along with C# to access a MySql database. To this point I have relied on Visual Studio to create the code for the DataSet, and that seems to have given me a problem. If the database is inaccessible (i.e. not running) it gives a "MySqlException was unhandled", "unable to connect to any of the specified MySQL hosts".

My question is what is the best way to handle this exception?

I would like to be able to handle it without tampering with the designer.cs file, but if that is not possible then any way of solving this will do.

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
    [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Fill, true)]
    public virtual int Fill(customerDataSet.addressesDataTable dataTable) {
        this.Adapter.SelectCommand = this.CommandCollection[0];
        if ((this.ClearBeforeFill == true)) {
            dataTable.Clear();
        }
// Exception occurs on the line below.
        int returnValue = this.Adapter.Fill(dataTable);
        return returnValue;
    }
A: 

When handling exceptions, you should catch the exception at the earliest moment you have something you want to do in response to the exception. A DataSet is a poor place to handle the event of your database being inaccessible; how will the rest of your application be notified that this error has occured?

In your case, how do you wish to handle this MySqlException being thrown? In most cases, an inaccessible database is going to be a difficult error to recover from. You may wish to let the exception bubble up through your current process and simply display an error message, or you might want to re-attempt the process, or you may wish to switch to another database.

It sounds to me that you might want to do some general reading around the purpose of exceptions and why the "throw" mechanism exists. They're not simply there to annoy you into writing try-catch blocks!

Programming Hero
I think you've made a good point there, I'll look into testing the connectionString before the DataSet is used. Will return a bit later with results.
I've created a separate method that attempts to open a connection, and if it fails it is caught and lets me know via message box that the connection failed without any crashing. It does what I need it to do so thank you for your help.