使用try catch块的C#Unhandled Exception

时间:2014-10-06 19:09:12

标签: c# exception webexception

我得到System.Net.WebException说:

  

远程服务器返回错误:(403)Forbidden。

这是我所期待的,因为使用http请求传入了无效的标头。但是,我的代码似乎没有像我期望的那样捕获异常。

以下是代码:

private void callback(IAsyncResult result)
{
    Debug.WriteLine("Callback");
    HttpWebResponse response = null;
    try
    {
        response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) 
                       as HttpWebResponse;
    }
    catch (WebException e)
    {
        Debug.WriteLine("Exception: " + e);
    }
    catch (Exception e)
    {
        Debug.WriteLine("Unknown exception: " + e);
    }
}

为什么没有捕获异常?

1 个答案:

答案 0 :(得分:0)

看看here

可能你应该这样做:

Task<WebResponse> task = Task.Factory.FromAsync(
    request.BeginGetResponse,
    asyncResult => { callback(asyncResult); },
    (object)null);

return task.ContinueWith(t =>
{
if (t.IsFaulted)
{
    //handle error
    Exception firstException = t.Exception.InnerExceptions.First();
}
else
{
    return FinishWebRequest(t.Result);
}
});