如何在C#中使用try catch发生错误

时间:2014-09-11 13:54:51

标签: c# cookies try-catch

我有这个页面请求一个将存储在DepartmentId中的cookie值,当一个cookie不存在时会发生错误。现在我想抓住那个错误,这样它就不会让我的服务器崩溃。我使用了一个普通的try catch语句,现在我需要知道是否还有其他方法来捕获错误,这是我的代码:

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);
    }
}

1 个答案:

答案 0 :(得分:1)

检查它是否为null的另一种方法可能是这样做:

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

else 
{
    //notify that the cookie is null
}