Reputation: 93565
I put a try/catch block around a bit of code that occasionaly throws an expected exception, but rather than catching it and displaying the message box, it stops the debugger and alerts me that the exception is unhandled.
How do I handle this exception so my code doesn't stop when the exception occurs?
Friend myDevInfo As New devInfo
''' <summary>
''' Closes the device handle obtained with CreateFile and frees resources.
''' </summary>
'''
Friend Sub CloseDeviceHandle()
Try
WinUsb_Free(myDevInfo.winUsbHandle)
If Not (myDevInfo.deviceHandle Is Nothing) Then
If Not (myDevInfo.deviceHandle.IsInvalid) Then
myDevInfo.deviceHandle.Close()
End If
End If
Catch ex As System.AccessViolationException
MsgBox("System.AccessViolationException")
Catch ex As Exception
Throw
End Try
End Sub
Upvotes: 4
Views: 2801
Reputation: 27
Use this attribute on the top of the function that you are using.
[HandleProcessCorruptedStateExceptions()]
This exception occurs with only unsafe or protected memory. The memory that is not been allocated . If you use this attribute then the clr will detect it and the try-catch block is working fine present in :
System.Runtime.ExceptionServices;
Upvotes: 1
Reputation: 11
An access violation exception falls into a class of exceptions called 'corrupted state exceptions'. With .Net 4, Microsoft took the decision that these should no longer be caught by try .. catch blocks. Their reasoning is that it takes understanding and care to recover from corrupted state exceptions without causing more damage, and that it is safer for users' data, if the application is closed down.
MSDN will tell you how to reverse this change
Upvotes: 1
Reputation: 2733
The try...catch
block should work as expected, when no debugger is attached.
You can define what exceptions the debugger breaks on under Debug -> Exceptions, I believe the default is to break on AccessViolationException
.
Upvotes: 3