0

I have a multi threaded .NET app that uses async I/O and AsyncCallbacks to handle the I/O completions. Rarely, the app will fail with an exception like:

Arithmetic operation resulted in an overflow.
   at MyApp.ReadComplete(IAsyncResult ar) in c:\MyApp.cs:line 123
   at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
   at System.Net.ContextAwareResult.CompleteCallback(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Net.ContextAwareResult.Complete(IntPtr userToken)
   at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
   at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

Line 123 in MyApp.cs is the first executable line of the AsyncCallback and it is inside of a try/catch (Exception ex) but, the catch is NOT being executed.

Is the .NET Framework lying to me about where the exception occurred? Did the exception actually occur out in the async netherworld where I can't catch it? Why can't I catch this exception?

John Vottero
  • 845
  • 1
  • 7
  • 24
  • 2
    This is a variant of a very old question: "Can God raise an exception that he cannot catch?" – Sedat Kapanoglu Apr 10 '09 at 17:31
  • I would not expect that could happen, at least not if the stack trace shows that the exception originated in your method. Could you post some code that reproduces the problem ? Also, have you checked InnerExceptions ? – driis Apr 10 '09 at 17:32
  • I cannot post code that reproduces the problem because I cannot induce an AritmeticException (or any other exception) during the async I/O. Any exception that I induce is caught as expected. There are no inner exceptions. – John Vottero Apr 10 '09 at 19:21

2 Answers2

3

Try to use catch instead of catch(Exception ex). This catches everything incl. COM exceptions.

crauscher
  • 6,528
  • 14
  • 59
  • 85
0

The actual answer is yes, the .NET Framework was wrong about where the exception occurred but, not because the exception occurred off in the async netherworld. The exception actually occurred in the callback method, many lines after the line indicated in the stack trace. The line where the exception actually occurred was NOT inside of a try/catch block so, the unhandled exception was expected.

I reported the incorrect stack trace to Microsoft but have no idea if it is considered a bug.

I think that it's safe to say that if your stack trace points to the first executable line of an async callback method, you should suspect that it could be wrong.

John Vottero
  • 845
  • 1
  • 7
  • 24