In my try/catch shown below, the application loops through the words that were entered into the textbox by the user. (I have already verified that this part works.) As it loops through the words it passes each word the function below.
private string runQuery(string data)
{
// Step 1 - Declare the query and parameters
SqlCeConnection connection = new SqlCeConnection(@"Data Source=keywordDB.sdf");
SqlCeCommand cmd = new SqlCeCommand("SELECT abbrev, description FROM abbreviations WHERE abbrev LIKE @abbrev", connection);
cmd.Parameters.AddWithValue("@abbrev", data);
SqlCeDataReader reader;
try
{
// Step 2 - Opens the connection
connection.Open();
// Step 3- Execute query and assign the data to abbrevQueryResult and results
reader = cmd.ExecuteReader();
reader.Read();
abbrevQueryResult = reader[0].ToString();
results = reader[1].ToString();
// Step 4 compare abbrevQueryResult to data entered by user in textbox
if (abbrevQueryResult.ToLower().Equals(data.ToLowerInvariant()))
{
returnResults.Append(" " + results + ",");
}
}
catch (InvalidOperationException e)
{
badData = new StringBuilder();
badData.Append(" " + data);
}
finally
{
if (connection != null)
{
connection.Close();
}
}
return returnResults.ToString();
}
I’ve noticed that if I enter in 6 words, 3 of which should work fine, and 3 which should be caught by the catch statement that the catch statement will only catch the very last one. Any idea why it only catches one of the words? I’d love for it to catch all of them and add them all to the StringBuilder badData.
You don’t show where
badDatais declared. However, every time your catch block gets called, you’re resettingbadDatato a new StringBuilder – meaning its old instance (and any values held within it) are discarded. If you remove this line within your catch block:you’ll probably be closer to where you want to be.
When you end up with a null pointer exception after doing this, you’ll need to ensure that
badDatais instantiated to= new StringBuilder();(as you had it) wherever you already have it declared – I.E., as an instance variable outside of the method.