Databases Reference
In-Depth Information
How It Works
First you create the data reader and try to access an invalid column:
// create data reader
SqlDataReader dr = cmd.ExecuteReader();
// access nonexistent column
string str = dr.GetValue(20).ToString();
so an exception is thrown because column 20, the value of which you try to get, doesn't
exist. You add a new catch clause to handle this kind of ADO.NET error.
catch (System.InvalidOperationException ex)
{
string str;
str = "Source: " + ex.Source;
str += "\n" + "Message: "+ ex.Message;
str += "\n" + "\n";
str += "\n" + "Stack Trace: " + ex.StackTrace;
MessageBox.Show (str, "Specific Exception");
}
When an exception of type System.InvalidOperationException is thrown, this catch
clause executes, displaying the source, message, and stack trace for the exception. With-
out this specific catch clause, the generic catch clause will handle the exception. (Try
commenting out this catch clause and reexecuting the code to see which catch clause
handles the exception.)
Next, you run the program for a nonexistent stored procedure.
// specify that a stored procedure is to be executed
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_Select_No_Employees";
You catch your (first) database exception with
catch (SqlException ex)
leading into the next topic: handling exceptions thrown by the database manager.
Search WWH ::




Custom Search