简体   繁体   中英

Proper way of using try catch() in C#

I am using ASP.NET/C# .

Here is an example where I am updating some information in database using lambda expression .

try
{
    using (var db = new DataClasses1DataContext())
    {
        var logSubGroup = db.sys_Log_Account_SubGroups
             .SingleOrDefault(subGroup => subGroup.cSubGroupName.Equals(subGroupName));
        logSubGroup.cRejectedBy = rejectedBy;
        logSubGroup.dRejectedOn = DateTime.Now;
        logSubGroup.cAuthorizedStatus = "Rejected";
        db.SubmitChanges();
    }
}
catch (Exception ex)
{
}

As you can see I am not doing anything inside catch() block .

I know this is a terrible way of using try catch .

Can anyone just help me to use try catch block in a correct manner.

I am just clueless as to what must come inside the catch block .

Any suggestions are welcome.

Don't use a try-catch block at all, unless you have a specific reason to catch a specific exception .

Instead, use one of the global exception handling methods ( Application_Error in ASP.NET) to globally catch unhandled exceptions, show an error message and log the error.

As a general rule, there is no need to catch an exception if the code catching the exception cannot do something about the problem, then continue running correctly. In code like what you've presented, can you identify some action you could take within the catch block to restore the program to a state where you trust it to continue running? If not, then just let the exception bubble up the stack.

You should ideally handle the error so that your application can recover from it, at the very least though, you should log it. You should never just swallow it. Also, you shouldn't handle an exception that you don't expect or can't handle. For example, when opening a file, a FileNotFoundException can be expected and handled, for example by displaying a warning and letting the user pick another file.

从理论上讲,由你来决定你的catch语句中可能出现什么样的异常当然,如果你处于开发阶段,这样做也不是完全错误的,我强烈建议不要尝试catch,因为你可能会错过一些重要的可能发生的异常,你也想修复一般你应该包括一个消息或一个动作,如果发现异常或错误,可以通知用户的消息可以通知操作没有很好地执行但理想情况下你必须让用户知道出了什么问题,所以在这种情况下,更好的错误处理是一种方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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