1

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);
}
Philip Atz
  • 886
  • 1
  • 10
  • 26

1 Answers1

7

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.

Community
  • 1
  • 1
Philip Atz
  • 886
  • 1
  • 10
  • 26
  • Holy crap, thanks for this, I had no idea. My company is slowly porting code from 3.5 to 4 so we'll most likely run into this issue. On the other hand what can make the driver crash? – Blindy Dec 09 '14 at 16:16
  • Bugs in unmanaged driver code (memory leaks, etc) in general, which is particularly likely if you are using old drivers. – Philip Atz Dec 09 '14 at 17:49