1

When a session variable reaches timeout a NullReferenceException is thrown. I know you can change how long it takes for the session variable to timeout. I'm trying to remove all possible ways for anything to crash. Is there any reason why the exception is not being caught here?

protected void Page_Load(object sender, EventArgs e)
{
     try
     {
        // Get session variables. 
        String strParticipantID = Session["ParticipantID"].ToString();
     }
     catch (NullReferenceException)
     {
            Response.Redirect("Login.aspx");
     }    
}
Support Ukraine
  • 978
  • 6
  • 20
Isiah Jones
  • 94
  • 1
  • 12

1 Answers1

3

You should never attempt to catch a NullReferenceException, nor should you manually throw it.
What you should do is write null-safe code - and that's pretty easy using the null conditional operator (?.) -

// This will never throw a null reference exception
var participantID = Session["ParticipantID"]?.ToString(); 

If you want an empty string instead of null, you can combine that with the null coalescing operator (??):

// This will never throw a null reference exception - 
// participantID will be an empty string if Session["ParticipantID"] is null.
var participantID = Session["ParticipantID"]?.ToString() ?? ""; 
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • I didn't work in my situation. An exception is still caught. The easy way for me was to change the session timeout for 24 hours. If someone is randomly on the website for that one and they click to refresh the page will still crash thou. – Isiah Jones Apr 12 '20 at 16:39
  • @isiah Did you mean that the exception is *thrown*? Was that maybe from another place in your code, like a PreRender? – Hans Kesting Apr 12 '20 at 17:04
  • Using the operators I've shown in my answer can't throw a null reference exception. What can happen is that in the first example `participantID` can be null, and in the second one it can be an empty string. – Zohar Peled Apr 12 '20 at 17:17
  • @ZoharPeled Well Visuall Studio still throws a null reference exception error an instance of an object that cannot be null. – Isiah Jones Apr 12 '20 at 18:18
  • Perhaps on `Session` itself? Are you sure that's from this line of code? – Zohar Peled Apr 12 '20 at 19:04