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.
}
}
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
streamturns out to benull.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/catchhere unless there was something specific I expected and wanted to handle somehow.