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