简体   繁体   English

在C#中使用try catch()的正确方法

[英]Proper way of using try catch() in C#

I am using ASP.NET/C# . 我正在使用ASP.NET/C#

Here is an example where I am updating some information in database using lambda expression . 这是一个使用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 . 正如你所看到的,我在catch() block没有做任何事情。

I know this is a terrible way of using try catch . 我知道这是使用try catch一种可怕方式。

Can anyone just help me to use try catch block in a correct manner. 任何人都可以帮助我以正确的方式使用try catch block

I am just clueless as to what must come inside the catch block . 关于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 . 除非您有特定原因要捕获特定异常 ,否则请勿使用try-catch块。

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. 相反,使用全局异常处理方法之一(ASP.NET中的Application_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? 在您所呈现的代码中,您是否可以确定可以在catch块中执行的某些操作,以将程序恢复到您信任它继续运行的状态? 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. 例如,在打开文件时,可以预期并处理FileNotFoundException,例如通过显示警告并让用户选择另一个文件。

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

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

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