为什么没有捕获NullReferenceException?

时间:2016-03-07 02:39:07

标签: c# exception

我在方法中有一个通用的Catch(Exception ex)块。那么为什么它没有捕获NullReferenceException异常呢?这种情况偶尔会发生一次。

public bool ChangeOrder(string conumber, string recepitnumber, string webServiceURL, string username, string password,ref string error)
{
    error = "";
    bool result = false;
    try
    {
        MovexAPI objMovexAPI = new MovexAPI();
        objMovexAPI.APIName = "ZOI100MI";
        objMovexAPI.TransactionName = "ChgHead";             
        objMovexAPI.URL = webServiceURL; 
        objMovexAPI.MaxRecords = 0;
        objMovexAPI.InputKeyValuePair = new Dictionary<string, string>();
        objMovexAPI.ReturnColumns = new List<string>();

        string url = objMovexAPI.URL + objMovexAPI.APIName + "/" + objMovexAPI.TransactionName;
        string returncols = string.Join(",", objMovexAPI.ReturnColumns.Select(s => s.ToString()).ToArray());
        string maxrecords = objMovexAPI.MaxRecords.ToString();
        string inputValues = "";

        objMovexAPI.InputKeyValuePair.Add("CONO", "100");
        objMovexAPI.InputKeyValuePair.Add("ORNO", conumber);
        objMovexAPI.InputKeyValuePair.Add("OREF", recepitnumber);

        foreach (KeyValuePair<string, string> kvp in objMovexAPI.InputKeyValuePair)
        {
            inputValues += kvp.Key + "=" + kvp.Value + "&";  //"?CONO=100&FACF=H01&FACT=H01&STSF=20&STST=90";
        }
        if (inputValues.Length > 0)
        {
            inputValues = inputValues.Substring(0, inputValues.Length - 1);
        }

        HttpWebRequest request = WebRequest.Create(url + "?" + inputValues) as HttpWebRequest;

        request.Credentials = new NetworkCredential(username, password);

        request.Accept = "application/json";
        request.ContentType = "application/json";

        // Get response  
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                result = true;
            }
        }
    }
    catch (WebException wex)
    {
        error = ((HttpWebResponse)wex.Response).StatusDescription;
        result = false;
    }
    catch (Exception ex) // Shouldn't this catch all exceptions ???
    {
        error = ex.Message;
        result = false;
    }
    return result;

}

异常堆栈跟踪如下所示,它清楚地表明在上述方法中发生了NullReferenceException。为什么不被Exception ex抓住?

Exception type: NullReferenceException

Exception message: Object reference not set to an instance of an object.

at StaffSales.M3.OutboundData.ChangeOrder(String conumber, String recepitnumber, String webServiceURL, String username, String password, String& error)

at StaffSales.BL.CustomerOrder.ApproveCOLines(String conumber, String recepitNo, String divi, String webServiceURL, String username, String password, List`1& APIErrors)
at StaffSales.Controllers.HomeController.ProcessPayment(COPaymentModel objModel)
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.b__32(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.b__1c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__1e(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.b__15(IAsyncResult asyncResult, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

1 个答案:

答案 0 :(得分:2)

这行代码可能是一个问题;

error = ((HttpWebResponse)wex.Response).StatusDescription;

根据MSDN文章https://msdn.microsoft.com/en-us/library/system.net.webexception.response(v=vs.110).aspx

WebException.Response Property

物业价值 键入:System.Net.WebResponse 如果Internet资源中有响应,则包含来自Internet资源的错误响应的WebResponse实例;否则,null。

这意味着您需要检查空值。

 if(wex.Response != null)
 {
     error = ((HttpWebResponse)wex.Response).StatusDescription;
 }