繁体   English   中英

尝试捕获异常

[英]try and catch exception

我想问一下在 asp.net 中使用 try 和 catch 是否有正确的语法

我的代码是这样的:

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

我的尝试和捕捉方向正确吗? 或者我应该使用这个。

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

非常感谢。

这是捕获所有异常的正确语法; 然而,这是一个非常糟糕的反模式。 这捕获了 ex 并立即再次抛出它,破坏了整个堆栈跟踪。 如果需要重新抛出,则写 throw;

在这种情况下,您根本不想抛出,因此空捕获可能是正确的。 考虑返回更多关于出错的信息,这需要将错误返回放在 catch 子句本身中。

唯一的区别是后者会在

if (ModelState.IsValid)

线。 除非您认为该行实际上可能会引发异常,否则它们是相同的。


您可能还想更多地考虑为异常设置如此广泛的网络(即缩小您想要处理的实际异常的范围)。 这个想法是处理你能做的,让其他一切通过上层来处理。

此外,最好通过throw本身而不是throw ex重新抛出异常。 前者保留了后者将丢失的信息。

但是,由于除了将异常传递到树上之外,您实际上没有对异常进行任何操作,因此首先捕获它没有任何意义。 只需执行命令,如果您遇到异常,更高级别的异常处理程序应该会处理它,而无需您使用try..catch

第二个选项更安全,因为它也涵盖了ModelState检查。 另外, throw ex; 不是个好主意。 你不会得到完整的堆栈跟踪。 使用throw;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM