简体   繁体   English

使用try catch块的C#未处理异常

[英]C# Unhandled Exception using try catch block

I'm getting a System.Net.WebException saying: 我得到一个System.Net.WebException说:

The remote server returned an error: (403) Forbidden. 远程服务器返回错误:(403)禁止。

This is what I'm expecting since invalid headers are being passed in with the http request. 这是我所期望的,因为将无效的标头随http请求传递进来。 However, my code does not seem to be catching the exception like I would expect. 但是,我的代码似乎并没有捕获我所期望的异常。

Here is the code: 这是代码:

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

Why is the exception not caught? 为什么未捕获到异常?

Take a look here . 在这里看看。

Probably you should do something like this: 可能您应该执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM