抛出WebException但永远不会被捕获

时间:2012-02-26 18:05:50

标签: c# .net exception exception-handling httpwebrequest

我有以下代码:

try
{
    using (var myHttpWebResponse = (HttpWebResponse) httPrequestCreated.GetResponse())
    {
        var streamResponse = myHttpWebResponse.GetResponseStream();

        if (streamResponse != null)
        {
            var streamRead = new StreamReader(streamResponse);
            var readBuff = new Char[256];
            var count = streamRead.Read(readBuff, 0, 256);         

            while (count > 0)
            {
                var outputData = new String(readBuff, 0, count);
                finalResopnse += outputData;
                count = streamRead.Read(readBuff, 0, 256);
            }
            streamRead.Close();
            streamResponse.Close();
            myHttpWebResponse.Close();

        }
    }
}
catch (WebException ex)
{
    MessageBox.Show("something went wrong");
}

错误代码是404 Not Found,但是我收到以下错误而不是MessageBox:

enter image description here

为什么异常从未被捕获?

2 个答案:

答案 0 :(得分:3)

您可能在Visual Studio中启用了第一次机会异常捕获。

尝试在没有调试器的情况下运行应用程序(Ctrl + F5)。或者,如果您收到此对话框,则可以按“运行”(F5)获取消息框。

答案 1 :(得分:0)

你确定你“抓住”同一类型的例外吗?而不只是WebException只抓住Exception,看看你是否得到MessageBox

    try
    {
        using (var myHttpWebResponse = (HttpWebResponse) httPrequestCreated.GetResponse())
        {
            var streamResponse = myHttpWebResponse.GetResponseStream();

            if (streamResponse != null)
            {
                var streamRead = new StreamReader(streamResponse);
                var readBuff = new Char[256];
                var count = streamRead.Read(readBuff, 0, 256);         

                while (count > 0)
                {
                    var outputData = new String(readBuff, 0, count);
                    finalResopnse += outputData;
                    count = streamRead.Read(readBuff, 0, 256);
                }
                streamRead.Close();
                streamResponse.Close();
                myHttpWebResponse.Close();

            }
        }

    }
    catch (Exception ex)
    {
        MessageBox.Show(string.format("this went wrong: {0}", ex.Message));
    }

编辑:看着你仔细观察我认为你看到之前的异常被扔到你的catch区块。在您的VS上按Ctrl + Alt + E并确保Throw Common Language Runtime Exceptions检查未选中