Null reference Exception unhandled by the user code - c#

I build my solution in visual studio(successfull) and I am trying to run it but for some reason at the following line of code it was throwing the exception I went several articles but there was no exact solution how this could be handled
public static int GetCurrentPolicyClassId()
{
**int policyClassId = (int) HttpContext.Current.Session[AppConstants.SK_POLICYCLASSID];**
return policyClassId;
}

One of the values in the chain you've called is null. You just need to check before getting the values:
if(HttpContext != null &&
HttpContext.Current != null &&
HttpContext.Current.Session != null &&
HttpContext.Current.Session[AppConstants.SK_POLICYCLASSID] != null)
{
// Get the value here.
}
else
{
// Something was null. Either set a default value or throw an Exception
}

You should probably check if HttpContext != null && HttpContext.Current != null && HttpContext.Current.Session != null

any exception is handled by try/catch (or finally), if that exception is possible to handle in general.
For example StackOverflowException could not be handled.
You need to:
what type of exception is
understand reasons of it
based on this decide if that exception is an exceptional behaviour in your application
if yes, handle it with try/catch if program needs to handle it, or leav program to fail, as the exception recieved is too dangerous and it's better to let to fail everything.
if this is not exceptional behavior, try to handle it with, for example null checks, or whatever...
Hope this helps.

Related

Why is this null check incurring a null dereference error?

So basically I want to check that a setting is not set in my C# application. The code here
if (Default["StudentAccountTypeDefault"] is null) // Crashes after this
{
//
}
else
{
//
}
seems to be crashing on the null-check. I've put a breakpoint there, and it shows Default["DefaultStudentAccountType"] to just be a blank string. Why is it crashing with a NullReferenceException? I'm pretty sure this is where it crashes-if I comment out if statement it works as expected.
Edit: To alleviate some confusion. Sooooo, Default is actually Settings.Default, and to add to that, I was actually trying to access it inside the Settings() constructor. So, before it had been initialized, obviously. Oops. "Full"-er code below.
public Settings() {
// // To add event handlers for saving and changing settings, uncomment the lines below:
//
// this.SettingChanging += this.SettingChangingEventHandler;
//
// this.SettingsSaving += this.SettingsSavingEventHandler;
//
if (Settings.Default["DefaultStudentAccountType"] is null)
{
}
else
{
}
}
You should be checking with == not with is, also depending on your data type you may need to check if Default is null too. Try this:
if(Default == null || Default["StudentAccountTypeDefault"] == null)
{
}
else
{
}
Default is a variable, so if it is null, accessing the indexer ["StudentAccountTypeDefault"] will throw a null reference exception.
If you're using a new enough .NET version, you can use:
if (Default?["StudentAccountTypeDefault"] is null)
(the null-coalescing operator). Otherwise, just check Default for null before using its indexer.

Throwing exceptions at multiple points (refactoring)

I'm writing a function that takes user input, runs a procedure in our database, and compares the values. Along the way, I need to check that we've received proper input and then that the query has returned an acceptable value.
private void DoTheThing(int? userInput1, int? userInput2, int valuePassedIn)
{
if (userInput1 == null || userInput2 == null)
{
Exception ex = new Exception();
ex.Data.Add("Message", "You screwed up.");
throw ex;
}
var queryResult = 0; //execute a query using the non-null inputs
if (queryResult == null) //or otherwise doesn't return an acceptable value
{
Exception ex = new Exception();
ex.Data.Add("Message", "some other thing happened");
throw ex;
}
else
{
//We're good, so do the thing
}
}
A quick note about this: I'm aware of the argument against exceptions as flow control and that I'd be better off checking the user's input before I even get this far. I won't get into all the details, but please accept that I'm kind of stuck writing the function this way.
That having been said, here's my question:
Given that the only differences between the 2 exceptions here is the message and the time at which they are thrown, how can I clean this code up to be both DRY and avoid running unnecessary code after determining that there will be a problem?
I thought about using a goto and placing the error code there, but that really only moves the problem around. If I move the exception code to the bottom and check for a message variable (or something similar), then I'm just running code that doesn't need to be run in the first place.
I suggest not throwing Exception (which means something went wrong, no comments are available), but ArgumentNullException and InvalidOperationException classes. Another amendment is avoding arrow-head
antipattern:
private void DoTheThing(int? userInput1, int? userInput2, int valuePassedIn)
{
// What actually went wrong? An argument "userInput1" is null
if (null == userInput1)
throw new ArgumentNullException("userInput1");
else if (null == userInput2)
throw new ArgumentNullException("userInput2"); // ...or userInput2 is null
var queryResult = executeSomeQuery(userInput1, userInput2, valuePassedIn);
// What went wrong? We don't expect that null can be returned;
// so the operation "executeSomeQuery" failed:
// we've provided validated (not null) values and got unexpected return.
// Let it have been known.
if (null == queryResult)
throw new InvalidOperationException(
String.Format("Query ({0}, {1}, {2}) returned null when bla-bla-bla expected",
userInput1, userInput2, valuePassedIn));
// We're good, so do the thing
// Note that's there's no "arrow-head antipattern":
// we're not within any "if" or "else" scope
}
Edit: Since every *Exception is inherited from Exception you can put some info into Data:
Exception ex = new ArgumentNullException("userInput1");
ex.Data.Add("Some key", "Some value");
throw ex;
but often Message is a far better place to explain what had heppened.
You might be better off creating a BadInputException class and a NullQueryResultException class. These do two different things and throwing a specific exception is better than throwing a generic Exception(...). In fact I think FXCop or Visual Studio's Code Analysis will give you a warning about throwing generic Exceptions.
It's not really all that much new code to write.
public class BadInputException : Exception
{
public BadInputException()
{
this.Data.Add("Message", "You screwed up.")
}
}
Then instead of this:
Exception ex = new Exception();
ex.Data.Add("Message", "You screwed up.");
throw ex;
Do this:
throw new BadInputException();
Edit: moved the "You screwed up" message from the Message property to the Data collection to match what the OP wants.
I would create a method:
private void CheckResult(bool cond, string msg, string info) {
if (!cond)
return;
Exception ex = new Exception();
ex.Data.Add(msg, info);
throw ex;
}
and call
CheckResult(userInput1 == null || userInput2 == null, "Message", "You screwed up.");
and
CheckResult(queryResult == null, "Message", "You screwed up.");
I think the QuestionRefactoring Guard Clauses is helpful for you .
There are something about this in Replace Nested Conditional with Guard Clauses.
Hope it's useful.

Method inexplicably continues after throwing an exception

The best explanation I have so far for this is "magic".
public string GetRouteSegmentData(RouteSegment RouteSegment, Exporter.RouteExporter Exporter)
{
try
{
List<RouteProviderSegmentData> List = Provider.GetSegments(RouteSegment);
}
catch (Exception e)
{
// logging and return null
}
}
// -----------------
// In the Provider class (more accurately, a child of a Provider class)
public override List<RouteProviderSegmentData> GetSegments(RouteSegment RouteSegment)
{
// CHECK 1
if (RouteSegment.RouteLineEntity == null) { throw new Exception("LineEntity null for route " + RouteSegment.Code); }
// CHECK 2
if (RouteSegment.RouteLineEntity.ListRouteLineParts == null) { throw new Exception("LineParts null for route " + RouteSegment.Code); }
// ...
}
So this is what happens: CHECK 1 is true, RouteLineEntity is in fact null, and when I debug it nicely steps into the "throw" part. But then... nothing seems to happen with that. The catch in GetRouteSegmentData() doesn't catch anything, it's like nothing was ever thrown. GetSegments() simply continues on to CHECK 2, and since RouteLineEntity is still null, this throws an exception (because I'm trying to access the ListRouteLineParts property of an object that's null), and this time that exception DOES get caught in GetRouteSegmentData().
So for some reason my manually thrown exception is blatantly ignored.
I've tried to put some code behind that first thrown, but this is never executed (as you'd expect, I guess).
What's going on here?

Null check returns true for non-null value

Having an odd problem. It's happened a few times over the years, but I've never been able to figure out why. Always solved it by rearranging the code I had in place, but would like to know is there's a more proper way of dealing with it, or at least figuring out what's behind it.
Non-working version:
public bool CaptureFrame(ArrayCache cache)
{
if (cache == null)
throw new ArgumentNullException("cache");
DataArray frame = cache.CacheData;
if (frame == null)
throw new ArgumentNullException("cache.CacheData");
// do stuff
}
Working version:
public bool CaptureFrame(ArrayCache cache)
{
if (cache == null)
throw new ArgumentNullException("cache");
if (cache.CacheData == null)
throw new ArgumentNullException("cache.CacheData");
DataArray frame = cache.CacheData;
// do stuff
}
The problem is this: frame is not null (at least according to the debugger, and by any measure I can trace of the code), however when it does the if (frame == null) check, it comes out true and throws the exception. I rewrote to check cache.CacheData and it works fine, but it really shouldn't make any difference to the code logic.
I managed to find one other question on the site with a similar problem, which ended up being related to the == and != operators being overloaded. Those operators are not overloaded for the class in question in my code, and it's a standalone class so there's nothing for it to inherit.
Edit: John Saunders requested code for the CacheData property:
private DataArray cacheData;
public DataArray CacheData
{
get
{
return cacheData;
}
set
{
cacheData = value;
}
}
looks like you are mapping the exception in the non working one then calling
DataArray frame = cache.CacheData;
but what if cache.CacheData if null then you are assigning it to DataFrame.. it's always best in my opinion to do the Check for null first before assigning or assuming your second one looks fine.. prehaps instead of throwing an exception maybe you could trap the exception and try some test cases for both scenarios

Which is correct way to check for Null exception?

Which is the most correct code?
if (HttpContext.Current.Response.Cookies[authCookieName] != null) {
HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value";
}
or
if (HttpContext.Current != null)
if (HttpContext.Current.Response != null)
if (HttpContext.Current.Response.Cookies != null)
if (HttpContext.Current.Response.Cookies[authCookieName] != null)
HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value";
If any one of HttpContext, HttpContext.Current, HttpContext.Current.Response, or Http.Current.Response.Cookies is null, you're already in trouble. Let the exception happen and fix your web server.
Both are good. Assuming that you have already checked everything else that need to be checked first. E.g.:
private bool CheckSuspendersAndBelt()
{
try
{
//ensure that true is true...
if (true == true)
{
//...and that false is false...
if (false == false)
{
//...and that true and false are not equal...
if (false != true)
{
//don't proceed if we don't have at least one processor
if (System.Environment.ProcessorCount > 0)
{
//and if there is no system directory then something is wrong
if (System.Environment.SystemDirectory != null)
{
//hopefully the code is running under some version of the CLR...
if (System.Environment.Version != null)
{
//we don't want to proceed if we're not in a process...
if (System.Diagnostics.Process.GetCurrentProcess() != null)
{
//and code running without a thread would not be good...
if (System.Threading.Thread.CurrentThread != null)
{
//finally, make sure instantiating an object really results in an object...
if (typeof(System.Object) == (new System.Object()).GetType())
{
//good to go
return true;
}
}
}
}
}
}
}
}
}
return false;
}
catch
{
return false;
}
}
(sorry, couldn't resist... :) )
could try:
if(HttpContext.Current != null &&
HttpContext.Current.Response != null &&
HttpContext.Current.Response.Cookies != null &&
HttpContext.Current.Response.Cookies[authCookieName] != null)
{
// do your thing
}
HttpContext.Current.Response.Cookies will never be null. The only thing that can cause a null is if the cookie you are expecting doesn't exist, so the first is correct. HttpContext.Current would be null if you weren't accepting a web request though :)
The first example you gave is more than enough. Like mentioned, if any of the other objects are null there is a problem with ASP.NET.
if (HttpContext.Current.Response.Cookies[authCookieName] != null) {
HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value";
}
But rather than littering your code with these often many checks, you should create some generic functions like SetCookie, GetCookie, GetQueryString, and GetForm, etc. which accept the name and value (for Set functions) as parameters, handle the null check, and returns the value or an empty string (for Get Functions). This will make your code much easier to maintain and possibly improve, and if you decide to use something other than Cookies to store/retrieve options in the future, you'll only have to change the functions.
Neither is really more correct, though I would avoid the second, as deeply nested conditionals tend to be hard to understand and maintain.
If you would prefer you get a null pointer exception, use the first. If you want to deal with nulls in another way or silently, use the second (or a refactored version of the second).
If you think there's a chance that Current, Response, Cookies, or Cookies[authCookieName] could be null, and you have a reasonable thing to do if any of them are, then the latter's the way to go. If the chances are low, and/or there's nothing you can do if the intermediates are null, go for the former, as it's more concise - the best you could do is to get better logging if you use the expanded example.

Categories

Resources