简体   繁体   中英

How to handle an error when it occurs using try catch in C#

I have this page which request a cookie value that will be stored in DepartmentId,when a cookie is not present an error occurs.Now I want to catch that error so that it doesn't crash my server. I've used a plain try catch statement,now I need to know if there is any other ways to catch the error here is my code:

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
        nvc.AddFromQueryString(Request.QueryString);
        nvc.AddFromQueryString("DepartmentID", HttpContext.Current.Request.Cookies["DepartmentId"].Value, Request.QueryString);

        StoredProcedureCaller spc = new StoredProcedureCaller();
        spc.Execute(nvc, Resources.StoredProcedureDefinitions.GetCurrentDowntimeEventForDepartment, Resources.ConnectionStrings.HestoNew);

        Response.Write(spc.ToString("json"));
    }
    catch (Exception ex)
    {
        Response.Write("Exception catch", ex);
    }
}

Another way of checking if it is null could be to do something like this:

if (cookie != null) 
{
    //do something
}

else 
{
    //notify that the cookie is null
}

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