views:

50

answers:

1

When using asynchronous code to read from streams etc using the BeginXXX / EndXXX pattern, I believe that any exceptions that occur during the process will be thrown when the call to EndXXX is made.

Does this mean that the initial call to BeginXXX will never throw an exception, it will always be thrown by EndXXX?

Or to put it another way, should I enclose BeginRead with try{}catch{} as well?

public StartReading()
{
        // Should this be enclosed with try{}catch{} ?
        stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(readCallback), stream);
}

private void readCallback(IAsyncResult result)
{
    Stream stream = (Stream)result.AsyncState;

    try
    {
        int len = stream.EndRead(result);

        // Do work...

    }
    catch(Exception ex)
    {
        // Error handling stuff.
    }
}
+2  A: 

Well, any code can throw an exception, so "never" is strong... for example, OutOfMemoryException, ThreadAbortException, or some other exception that indicates resource saturation (for example, it somehow can't start the async operation).

It might (although I haven't tested) also throw immediately if that is a write-only stream. And it will certainly throw immediately if stream turns out to be null.

However! In all the cases I've mentioned, the correct behaviour is probably to let it bubble up; they all indicate pretty fundamental problems unrelated to the current logic. So no: I wouldn't try/catch here unless there was something specific I expected and wanted to handle somehow.

Marc Gravell
@Marc : I figured that 'never' would generate an opinion :) The code posted was just a skeleton to explain my question, so, assuming I do proper checks on the parameters passed to BeginXXX, any exceptions will not be specific to the call itself, but rather for the application as a whole?
Andy
@Andy - exceptions relating to *reading the data* should come out from `EndXXX`. "Braindead exceptions" (see Eric Lippert's blog) or sickly-process exceptions can come from anywhere.
Marc Gravell
@Marc : Thanks. +1 for the 'Braindead exceptions' reference alone!
Andy