I have an automated script written in C# that runs a stored procedure on SQL Server 2014. The stored procedure is running multiple select, update, and insert statements and utilizes a try catch rollback pattern to catch and rollback the entire transaction when there's an exception.
It looks similar to this:
BEGIN TRY
BEGIN TRANSACTION TransName
--Lots of SQL!
COMMIT TRANSACTION TransName
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION TransName;
THROW
END CATCH
My C# that calls the procedure looks similar to this:
using (SqlCommand Command = new SqlCommand(query, Connection))
{
// Retry several times if the query fails.
for (var retry = 0; retry < 5 && !Success; ++retry)
{
try
{
Command.ExecuteNonQuery();
Success = true;
}
catch (SqlException e)
{
// Handling for Timeout or deadlocks.
// If not a timeout or deadlock and retry hasn't happened 4 times already.
if (!(e.Number == 1205 || e.Number == 1204 || e.Number == -2) || retry == 4)
{
LogException(e);
}
else if (e.Number == 1205 || e.Number == 1204)
{
// Wait to avoid hammering the database.
Thread.Sleep(500);
}
else if (e.Number == -2)
{
// Wait to avoid hammering the database.
Thread.Sleep(5000);
}
Success = false;
}
}
}
I have it looping to make sure the SQL goes through if there is a deadlock or timeout since it's an automated script.
In my logs for the script I can see that the stored procedure did not log any exceptions, but none of the data exists in the tables that the procedure touches which brings me to my question:
Is it possible for an exception to be caught in T-SQL and then thrown again using a T-SQL THROW statement but then the exception is not thrown in a C# client?
Let me know if I can clarify anything. Thanks!