为什么我的异常处理代码不处理异常?

时间:2009-09-01 16:10:41

标签: c# asp.net

我有一些C#代码使用HttpWebRequest类来下载远程网站。我正在用try / catch处理错误,但是一些错误(比如Webrequest和IOException)似乎没有被我设置的方式“抓住”:

try
{
    StartScrap("http://www.domain.com");
}
catch (Exception ex)
{
    LogError(ex.ToString();
}


private void StartScrap(string url)
{
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

    HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = response.GetResponseStream();
        string responseText = String.Empty;

        using (StreamReader readerStream = new StreamReader(responseStream, System.Text.Encoding.UTF8))
        {
            responseText = readerStream.ReadToEnd(); <-- I will sometimes get a Webexception error here that won't get caught above and stops the code
        }
    }
}

更新:代码还有更多内容,所以可能是我发布的代码之外的东西?我基本上在具有NotifyIcon的表单上的Windows应用程序中使用此代码。我正在使用Timer类以特定的计时器间隔运行代码。这就是我设置它的方式:

    public TrayIcon()
    {
        InitializeComponent();
    }

    private void TrayIcon_Load(object sender, EventArgs e)
    {
        try
        {
            StartScrap("http://www.domain.com");
        }
        catch (Exception ex)
        {
            LogError(ex.ToString());
        }
        finally
        {
            StartTimer();
        }
    }

    private void StartTimer()
    {
        Timer Clock = new Timer();
        Clock.Interval = 600000;
        Clock.Start();
        Clock.Tick += new EventHandler(TrayIcon_Load);
    }

4 个答案:

答案 0 :(得分:3)

“停止代码”究竟是什么意思?您是否有机会在调试器中运行?我的猜测是,如果你在调试器之外运行 - 或者只是在调试器中再次点击“run” - 你将进入catch块而没有任何问题。或者,进入调试器设置并更改调试器进入的位置。

当然,如果调试器中没有 ,我们只需要更多关于您所看到的内容的信息。

答案 1 :(得分:2)

可能是LogError引发异常吗?

答案 2 :(得分:0)

坦率地说,我不确定到底发生了什么,但我建议你选择ELMAH。(错误记录模块和处理程序)

Here是一步一步如何为ELMAH。

答案 3 :(得分:0)

没关系,我发现我调用了错误的函数我的Timer类,它绕过了事件处理程序。