Welcome to weblogs.com.pk Sign in | Join | Help

Using Try/catch to clean the code

Try/catch can let us write much cleaner code. Here is one example:

 

//Original Version

public void AddCarrier(System.Web.UI.WebControls.TextBox txt, System.Web.UI.WebControls.Label lbl)

{

      if (txt.Text.Length>0)

      {

            try

            {

                  int r = DBMartHelper.AddCarrier(txt.Text);

                  if (r>0)

                  {

                        lbl.Text = "Carrier added";

                  }

                  else

                  {

                        lbl.Text = "Error occurred";

                  }

            }

            catch (Exception ex)

            {

                  lbl.Text = ex.ToString();

            }

      }
      else
      {
            lbl.Text = “Empty textbox“;
      }

}

 

//Improved Version

public void AddCarrier(System.Web.UI.WebControls.TextBox txt, System.Web.UI.WebControls.Label lbl)

{

      try

      {

            if (txt.Text.Length <= 0) throw new System.ApplicationException("Empty textbox");

            int r = DBMartHelper.AddCarrier(txt.Text);

            if (r <= 0) throw new System.ApplicationException("Unable to add carrier");

            lbl.Text = "Carrier added";

      }

      catch (Exception ex)

      {

            //Log ex

            lbl.Text = ex.Message;

      }

}

Published Friday, February 04, 2005 9:08 PM by khurram
Filed under:

Comments

No Comments

New Comments to this post are disabled