c# - WebRequest.GetResponse().GetResponseStream() 可以在没有 WebException 的情况下返回 null 吗?

标签 c# .net error-handling resharper

Resharper 发出警告

Possible 'null' assignment to entity with '[NotNull]' attribute

对于线路

var strmR = new StreamReader(replyStream);

在以下代码中(删除了详细的异常处理)。

        Stream replyStream;
        string reply;

        var query = _serverBaseUrl + queryText;
        var wreq = WebRequest.Create(query);
        wreq.Timeout = _serverTimeoutLimit;
        try
        {
            replyStream = wreq.GetResponse().GetResponseStream();
            var strmR = new StreamReader(replyStream);
            reply = strmR.ReadLine();
        }
        catch (WebException webex)
        {
            switch (webex.Status)
            {
              /*throw new exceptions*/
            }
        }
        replyStream.Close();
        return reply;

我的想法是,我不需要检查 replyStream 是否为 null,因为 WebException (或未处理的异常)应该已经被抛出(然后我处理它)如果发生任何错误,则抛出新的自定义异常。

是否有可能在没有抛出 WebException 的情况下,replyStream 为 null?

最佳答案

replyStream 不能为 null。如果 GetResponse() 成功,GetResponseStream 始终有一个值。如果出现任何问题,则会引发 WebExceptiondocumentation of GetResponse()说以下内容

If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.

因此,您也可以将 catch 子句扩展为句柄 webex.Response

关于c# - WebRequest.GetResponse().GetResponseStream() 可以在没有 WebException 的情况下返回 null 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40907306/

相关文章:

c# - Resharper 在代码清理时围绕 NUnit [SetUp] 区​​域

c# - 如何获取包含日期的单元格的值并使用 NPOI 保留原始格式

c# - 模拟 DbContext - 无法插入新对象

c# - 如何在 Visual Studio 2017 中启用 C# 中的代码建议功能?

c# - 在Powershell中列出.NET namespace 的类?

c# - Listview ItemSelectionChanged,如何取消/撤消

linux - 出现错误 : set +e does not seem to do the job 时自动退出 bash shell 脚本

vba - VBA错误处理: Application.setOption and Application.setOption

c# - 在 C# 中选择单词部分

java - 如何使用 try{ }catch(){ } block 显示详细的错误消息