0

I am pretty new to C#. I am currently writing a WebSocket application, and I need to handle the NullReferenceException when the client disconnects, as I am constantly reading data from ClientSocket.

So the trouble is: When I place the second try-catch block inside the first one, I am able to catch the NullReferenceException. But when I remove the nested try-catch and try to catch the mentioned exception, it goes straight to the "finally" block.

    try
    {
        using StreamReader streamReader = new StreamReader(stream);

        while (true)
        {
            try
            {
                command = streamReader.ReadLine().Trim();
            }
            catch (NullReferenceException)
            {
                blah-blah
                break;
            }
        }
    }
//I place the NullReferenceException when removing the nested try-catch
    catch (Exception e)
    {
        blah-blah
    }
    finally
    {
        blah-blah
    }
Abraham
  • 185
  • 1
  • 10
  • `NullReferenceException` is entirely avoidable here and therefore so is the inner `try`/`catch`. ***Always*** check the return value of `ReadLine` for `null`. It [does so at the end of input](https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader.readline#return-value), which is not an exceptional condition, whereas calling a method on `null` is. – madreflection May 14 '20 at 02:51

2 Answers2

0

You'll need to check exception type on the outer catch or simply throw NullReferenceException again from the first catch.

0
using (StreamReader streamReader = new StreamReader(stream))
{
    while (true)
    {
        try
        {
            command = streamReader.ReadLine().Trim();
        }
        catch (NullReferenceException)
        {
            blah-blah
            break;
        }
    }
}

more like your streamReader is null.

urlreader
  • 6,319
  • 7
  • 57
  • 91