【问题标题】:C# Unhandled Exception using try catch block使用 try catch 块的 C# 未处理异常
【发布时间】:2014-10-06 19:09:11
【问题描述】:

我收到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);
    }
}

为什么没有捕获到异常?

【问题讨论】:

标签: c# exception webexception


【解决方案1】:

看看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);
}
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 2018-12-13
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    相关资源
    最近更新 更多