Search code examples
vb.netexceptionunhandled-exceptionunhandled

Getting an unhandled exception with a defined catch block


So I'm working in VB.Net and I am occasionally getting an unhandled exception. What I don't get is that I have a catch block for said exception.

Here's a sample of what I'm talking about.

        Try
            If MyTask3 IsNot Nothing Then
                MyTask3.Control(TaskAction.Abort)
                MyTask3.Dispose()
            End If
        Catch ex As DaqException
            ErrorMessage = ex.ToString()
            MyTask3.Dispose()
        Catch ex As AccessViolationException
            ErrorMessage = ex.ToString()
            MyTask3.Dispose()
        Catch ex As ObjectDisposedException
            ErrorMessage = ex.ToString()
        Catch ex As Exception
            ErrorMessage = ex.ToString()
        Finally
            Task3Aborted = True
        End Try

So in testing the above code snippet, I sometimes get an AccessViolationException (which the debugger says is unhandled even though there is a Catch for it). I step through the code and the catch that execute is the ObjectDisposedException.

So is this a case where I'm getting two exceptions thrown and only one is handled while the other is unhandled? Is that even possible?

Thanks in advance for any help.


Solution

  • Starting with the .NET Framework 4, AccessViolationException exceptions thrown by the common language runtime are not handled by the catch statement in a structured exception handler if the exception occurs outside of the memory reserved by the common language runtime. To handle such an AccessViolationException exception, you should apply the HandleProcessCorruptedStateExceptionsAttribute attribute to the method in which the exception is thrown.

    I think this is your problem. You can read more here.
    Mark the function with the HandleProcessCorruptedStateExceptions attribute to handle this exception. You may need to add legacyCorruptedState­­ExceptionsPolicy=true to your app.config.
    You can read this if you want to understand whats happening.