简体   繁体   中英

Null reference Exception unhandled by the user code

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
}

您可能应该检查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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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