c# - 我应该在哪里放置try catch?

标签 c# .net exception try-catch

学习记录错误。 这是贯穿我的项目的基本代码结构。

有人建议我只能将 try block 放在事件处理程序中。 但是在记录错误时,需要知道是哪个方法导致了错误。 因此,在这种情况下,我是否还应该在 AllIsFine()SaveData() 中保留 try block 。 如果是,那么它应该记录错误还是只是throw

什么是最佳/标准做法。

DataContext objDataContext = new DataContext();
protected void btn_Click(object sender, EventArgs e)
{
  try
   {
     if(AllIsFine())
      {
        objDataContext.SaveData();
      }
   }
  catch(Exception ex)
   {
     //some handling
   }
}

private bool AllIsFine()
{
   //some code
}

编辑:当然,我们会尝试确保它从不引发异常,但不切实际。我是这样看的。部署后,我唯一的访问权限是日志,需要尽可能多地获取信息。因此在这种情况下(以及这种结构),您建议将 try catch 放在哪里

最佳答案

I have been advised that the try block has to be placed only in Event Handlers

这不是真的。
有不同类型的异常,有些你需要处理,有些你应该抛出,有些你应该捕获,有些你不应该。阅读this请。

总结:

  • 你应该捕获异常,以便你可以对它们做一些事情
  • 如果你只想记录异常 catch、log,然后使用 throw 而不是 throw ex(它会重置调用堆栈)
  • 尽可能防止异常发生,检查防止异常发生的条件(IndexOutOfRangeExceptionNullPointerExceptionArgumentNullException)这样做而不是执行 Action 并捕获异常
  • Don’t catch fatal exceptions; nothing you can do about them anyway, and trying to generally makes it worse.
  • Fix your code so that it never triggers a boneheaded exception – an "index out of range" exception should never happen in production code.
  • Avoid vexing exceptions whenever possible by calling the “Try” versions of those vexing methods that throw in non-exceptional circumstances. If you cannot avoid calling a vexing method, catch its vexing exceptions.
  • Always handle exceptions that indicate unexpected exogenous conditions; generally it is not worthwhile or practical to anticipate every possible failure. Just try the operation and be prepared to handle the exception.

关于c# - 我应该在哪里放置try catch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27397620/

相关文章:

c# - 如何将控制反转 (IoC) 与 Azure 辅助角色结合使用

.net - 暂停 GACUTIL.exe 列表

php - 最佳替代异常处理模型

python - 如何检索函数或方法的异常列表

python - MySQL 1045 异常

c# - 这种情况下如何使用AutoFixture呢?

c# - 使用公共(public)领域的最佳做法是什么?

C# - 以编程方式打开和关闭 excel 文件的正确方法

c# - 将数据表转换为私有(private) List<List<string>>?

c# - SQL 字符和 C# 之间的转换