.netCoders Contact Us
Search:

Data Errors

Data errors are exceptions that happen when working with databases, such as SQL Server. These could be syntax errors in your SQL, or exceptions encountered while processing stored procedures. Database security can also be the source of data errors. The root of all Exceptions is the System.Exception class. For general ADO.NET errors, the System.Data.DataException class serves as a base class. Depending on the client library you use to access the database, more specific exceptions will either be SqlExceptions or OleDbExceptions.

SQL Server Errors

When using the System.Data.SqlClient namespace, and the classes contained within, for accessing a SQL Server database, data exceptions derive from the System.Data.SqlClient.SqlException class. For instance, the following list describes the cases where a SqlException will be thrown:
  • Bad username/password credentials
  • SQL Syntax Errors
  • Permission errors
  • Errors in executing Stored Procedures

You can check for these exceptions using standard try..catch syntax. The following code snippet shows error handling around some SQL code using the SqlClient classes:

try
{
    //Open connection with bad password to generate exception
    SqlConnection nwindConn = new SqlConnection("Data Source=localhost;User ID=sa;Password=badpassword;Initial Catalog=northwind");
    nwindConn.Open();

    //Do some work...

    //Cleanup
    nwindConn.Close();
}
catch (SqlException ex)
{
    MessageBox.Show("Sql Exception Encountered : " + ex.Message);
}

The Errors property returns a SqlErrorCollection of SqlError objects that contain the error information returned from SQL Server.