我有一些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);
}
这正是启动屏幕刮板的代码吗?如果你在后台线程中运行这个脚本,并且try/catch在主线程中,那么你会得到你得到的结果。 – 2009-09-01 16:23:40
上面的代码在LogError中缺少一个右括号(ex.ToString();(它永远不会编译) – 2009-09-01 16:26:09