Thursday, May 24, 2012

Customising exception with SPException class

I found this approach for handling the excepting in SharePoint 2010 is an elegant way. I simply pass the System Exception to SPException class and retrieved the exception details. Previously I have used the using operator to suppress the exception and clean carbage collection on my coding. But there were plenty of situation to capture the error and log into the database or system file. Here I have used to log the error details with inputs and result in the SharePoint List. I need to check this code and refine using "SPDisposeChecker tool".
protected void Button1_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(TextBox1.Text) && !String.IsNullOrEmpty(TextBox2.Text))
            {
                int a = Convert.ToInt32(TextBox1.Text);
                int b = Convert.ToInt32(TextBox2.Text);
                SPSite site=null;
                SPWeb web=null;
                SPList list=null;
                SPListItem item=null;

                try
                {

                    site = SPContext.Current.Site;
                    web = site.OpenWeb();
                    list = web.Lists["Calc"];
                    item = list.Items.Add();
                    item["A"] = a;
                    item["B"] = b;
                    Label1.Text = (a / b).ToString();
                    item.Update();

                }

                catch (Exception ex)
                {
                    SPException ex1 = new SPException(ex.Message, ex);

                    item["A"] = a;
                    item["B"] = b;
                    item["Result"] = ex1.Message;
                    item.Update();
                }

            }
        }