【问题标题】:C# can't avoid nested try-catchC# 无法避免嵌套的 try-catch
【发布时间】:2020-08-30 10:33:00
【问题描述】:

我对 C# 很陌生。 我目前正在编写一个 WebSocket 应用程序,我需要在客户端断开连接时处理 NullReferenceException,因为我一直在从 ClientSocket 读取数据。

所以问题是: 当我将第二个 try-catch 块放在第一个块中时,我能够捕获 NullReferenceException。 但是当我删除嵌套的 try-catch 并尝试捕获提到的异常时,它会直接进入“finally”块。

    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
    }

【问题讨论】:

  • NullReferenceException 在这里是完全可以避免的,因此内部的try/catch 也是如此。 总是检查ReadLine 的返回值是否为null。它does so at the end of input,这不是一个例外情况,而在null 上调用一个方法是。

标签: c# exception nullpointerexception try-catch try-catch-finally


【解决方案1】:

您需要检查外部捕获的异常类型,或者只是从第一个捕获中再次抛出 NullReferenceException。

【讨论】:

    【解决方案2】:
    using (StreamReader streamReader = new StreamReader(stream))
    {
        while (true)
        {
            try
            {
                command = streamReader.ReadLine().Trim();
            }
            catch (NullReferenceException)
            {
                blah-blah
                break;
            }
        }
    }
    

    更像是您的 streamReader 为空。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-09
      • 2014-08-23
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多