I am having a problem with a database call that throws an AccessViolationException
when I call ExecuteNonQuery()
. The call is enclosed in a try-catch
block but the exception is never caught. Instead, I get an entry about it in the Windows Event log. Is there a way of catching this exception in code?
IDbCommand cmd = ...
cmd.CommandText = "...";
try
{
var results = command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.Writeline("Caught exception: " + ex.Message);
}
ExecuteNonQuery()
can throw an AccessViolationException
if an underlying driver crashes in native mode. Starting with the .NET Framework 4, managed code no longer catches these types of exceptions in catch blocks. You can read more about this here.
The solution is to either set the <legacyCorruptedStateExceptionsPolicy>
element's enabled attribute to true in App.config, or to apply the [System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute]
attribute to the method containing the try-catch block.