I would like to ask if I'm getting a right syntax in using the try and catch in asp.net
My code goes like this:
public ActionResult Add_RefPerson(rms_referred_person ref_person) { if (ModelState.IsValid) { try { ref_person.rf_referreddate = Date(); ref_person.rf_createdby = getBadge(); ref_person.rf_updatedby = null; ref_person.rf_updateddate = null; ref_person.rf_isactive = true; db.rms_referred_person.Add(ref_person); db.SaveChanges(); return RedirectToAction("Index"); } catch (Exception ex) { throw ex; } } return Content("<script type='text/javascript'>alert('Cannot be saved');</script>"); } Is my try and catch in the right direction? or should I use this one.
public ActionResult Add_RefPerson(rms_referred_person ref_person) { try { if (ModelState.IsValid) { ref_person.rf_referreddate = Date(); ref_person.rf_createdby = getBadge(); ref_person.rf_updatedby = null; ref_person.rf_updateddate = null; ref_person.rf_isactive = true; db.rms_referred_person.Add(ref_person); db.SaveChanges(); return RedirectToAction("Index"); } } catch (Exception ex) { throw ex; } return Content("<script type='text/javascript'>alert('Cannot be saved');</script>"); } Thanks a lot.
throw;.,throw ex;obliterates the stack trace from the exception.catch (Exception ex)let alone docatch (Exception ex) { throw ex; }. The former is a bad practice and the latter is just terrible. You should only ever handle an exception that is truly exceptional and that you can recover from. Otherwise let the exceptions bubble to the top. Your code will have less bugs and be more maintainable if you do.