Friday, February 10, 2012

Clearing Exception in Catch block

Is there any way to clear out the exception from a previous Try/Catch block if I am nesting another Try/Catch block within it. I am executing a SQL Command and based on the Error number coming back decide whether or not to execute various other Sql commands. Now the Outer exception seems to be taking precedence over the Inner try block, and even though the code is stepped through for the inner try block it is never executed due to the Parent Exception. Is there any way to clear the exception received from the outer Try block? Here is a snippet of code:

Try

Cmd = New SqlCommand(Sql, Con)

Cmd.ExecuteNonQuery()

Catch t as SqlException

if t.Number = "2601" then

sql_upd = "<Text>"

Try

Cmd_upd = New SqlCommand(Sql_upd, Con)

Cmd_upd.ExecuteNonQuery()

Catch b as Exception

response.write("<Text>")

End Try

End If

End Try
Thanks,How do you know its never executed? Nesting try...catch should be fine. Just for good measure I even tried the following out


try
{
Console.WriteLine("1st");
throw new System.ArgumentException("bla");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
try
{
Console.WriteLine("2nd");
throw new System.ArgumentException("bla2");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

I suggest, if no other reason than to convince yourself, that you rewrite it to break the inner block out. So store the error in a var and test for it in a separate block. It shouldn't make a difference. I have noticed that the debugger can go a bit mad when dealing with exceptions so it might be that it's fooling you.|||I was debating on breaking it out, but since I think it should work as well I did not want to do it that way. However, when the code executes I know that it gets into the Second Try block , by using display messages, but the update statement is not executed. I have reviewed the output from the command to determine that. All that the debugger is displaying is the previous error message where I am trying to execute the new block.|||Ah now this maybe a red herring but then again maybe not (big this might be a load of **** warning). In the bad old days SQL Errors were accessed on the connection object. It maybe that SQL Errors are always held on the connection object but .NET exposes them as proper exceptions. Try turning on your SQL profiler to see if the 2nd command is executed. If not try creating a brand new connection object in the inner handler.

No comments:

Post a Comment