Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a generic Catch(Exception ex) block in method. So why it is not catching that NullReferenceException exception ? This happens just once in a while.

C#
 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;

}



Exception stack trace is as below which clearly indicates that NullReferenceException occurred in the above method. Why is it not being caught by 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.<begininvokesynchronousactionmethod>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.<invokeactionmethodfilterasynchronouslyrecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<invokeactionmethodfilterasynchronouslyrecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.<begininvokeactionmethodwithfilters>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.<begininvokeaction>b__1c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<begininvokeaction>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.<beginexecutecore>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.<beginexecute>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.<beginprocessrequest>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)

What I have tried:

The problem is application works OK 99.9% of the times. Just once in a while this error occur and I am staring at my code trying to find explanation for this. Why is catch not working ?
Posted
Updated 7-Mar-16 2:00am
Comments
Peter_in_2780 6-Mar-16 21:36pm    
Just a thought. The statement / error = ""; / is outside your try block.
virang_21 6-Mar-16 21:47pm    
error is passed to method as "ref string error". I am just setting it to empty string. Evan if its value is null that will not result in NullReferenceException as first thing method does is set it to empty string.

This is how method is called from application

string error = "";
OutboundData objOutbound = new OutboundData();
objOutbound.ChangeOrder(conumber, recepitNo, webServiceURL, username, password, ref error);
virang_21 6-Mar-16 22:30pm    
it turns out that this innocent looking line in the catch block is the culprit.

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

if wex.Response is null this will result in exception which is not handled.

1 solution

As you found out, it was actually in your first catch that was causing it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900