Home > Net >  Why is the SqlException not being thrown/caught?
Why is the SqlException not being thrown/caught?

Time:03-26

I have the following code in a library to perform a delete operation on database records. My code uses the Dapper library. The error is happening when I call the Dapper Execute() method.

Some of the database table records can not be deleted because they are referenced by related records in other tables. When a record can't be deleted, the database error "The DELETE statement conflicted with the REFERENCE constraint" happens (as expected). This error causes a System.Data.SqlClient.SqlException when calling Execute, and this exception crashes my program.

I wrote a try/catch to handle this error, but the program still crashes in the try and doesn't move to the catch block. It seems that maybe Execute() doesn't throw the exception? I've also tried using the Query() method with the same outcome. I am at a loss as to how I can catch and deal with this exception!

private IDbConnection db;

public Repository(string connectionString)
{
    db = new SqlConnection(connectionString);
}

public void DeletePerson(string PersonID)
{
    string query = "DELETE FROM PERSON WHERE PersonID = @PersonID";

    try
    {
        db.Execute(query, new { PersonID });  //program crashes here b/c of SqlException
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Here is the code that calls this method (from a different project). It is also in a try/catch, but the catch is never reached.

string id = "BELWIT";
try
{
    conn.DeletePerson(id);
}
catch
{
    MessageDialog errorMsg = new MessageDialog("Delete failed.");
    errorMsg.ShowAsync();
}

CodePudding user response:

It seems like errorMsg.ShowAsync() is an async method. One possibility is that you are not awaiting that method, so the program finishes execution before it can show that message. Can you try changing it to

await errorMsg.ShowAsync();

You'll also need to mark whatever method is calling that as async.

CodePudding user response:

It looks like this error was actually caused by my Visual Studio settings.

There was a checkbox in Exception Settings where 'Break When Thrown' was checked for System.Data.SqlClient.SqlException. So it was breaking and stopping execution in Visual Studio. Ignoring the exception popup and clicking 'Continue' allowed my code to move on to the catch block.

Dumb outcome and considered deleting, but maybe leaving it here in case anyone else experiences the same issue could be helpful?

  • Related