简体   繁体   English

如何捕获 System.NullReferenceException?

[英]How to catch System.NullReferenceException?

When a session variable reaches timeout a NullReferenceException is thrown.当 session 变量超时时,会引发NullReferenceException I know you can change how long it takes for the session variable to timeout.我知道您可以更改 session 变量超时所需的时间。 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");
     }    
}

You should never attempt to catch a NullReferenceException , nor should you manually throw it.您永远不应该尝试捕获NullReferenceException ,也不应该手动抛出它。
What you should do is write null-safe code - and that's pretty easy using the null conditional operator ( ?. ) -你应该做的是编写空安全代码——这很容易使用null 条件运算符 ( ?. ) -

// 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 ( ?? ) :如果您想要一个空字符串而不是null ,您可以将其与null 合并运算符 ( ?? )结合使用:

// This will never throw a null reference exception - 
// participantID will be an empty string if Session["ParticipantID"] is null.
var participantID = Session["ParticipantID"]?.ToString() ?? ""; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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