Catching exceptions using BeginRead in C #

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

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

Or, in another way, should I include BeginRead with try {} catch {}?

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.
    }
}
+3
source share
2 answers

, , "" ... , OutOfMemoryException, ThreadAbortException , (, - ).

( ) , . , stream null.

! , , , , ; , . , : try/catch , - , , - .

+2
source

Simple proof:

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

So you should expect an exception here.

+1
source

Source: https://habr.com/ru/post/1756315/


All Articles