【问题标题】:Exception Handling Best-Practice异常处理最佳实践
【发布时间】:2018-01-03 01:41:05
【问题描述】:

如果我调用了两个可以互相抛出相同异常的方法,但是异常的根据不同,我应该如何处理呢?

我是否应该在每个方法周围放置一个 try catch 块,以便我可以以不同的方式处理这两个异常,或者如何获取引发异常的方法?

例如: 我有这个方法

dir = Directory.CreateDirectory(Path.Combine(My.Settings.CalibrationExcelExportPath, dirName)) 

该方法可以抛出一个IOexception

接下来我调用一个方法 ExcelExport.ExportCalibrationAsync 创建一个 TempFile,它也可以抛出一个 IOexception,例如,如果没有更多的临时名称可用。

现在我想在差异中处理异常。向用户提供正确信息的方法。

我试过exception.TargetSite,但我两次都得到Void WinIOError(Int..),所以我不能用它来区分。

这里的最佳做法是什么

【问题讨论】:

    标签: .net vb.net exception


    【解决方案1】:

    我建议您创建自定义异常,因为您的调用堆栈可能很深,并且您的处理程序可能与异常来源的方法不同。

    Try
        dir = Directory.CreateDirectory(Path.Combine(My.Settings.CalibrationExcelExportPath, dirName
    Catch ex As Exception
        Throw New CreateDirectoryException("An exception has occurred when creating a directory.", ex)
    End Try
    
    Try
        ' Other code causing exception here
    Catch ex As Exception
        Throw New AnotherException("An exception has occurred.", ex)
    End Try
    

    比为CreateDirectoryExceptionAnotherException 创建任何你喜欢的处理程序。

    【讨论】:

      【解决方案2】:

      我将讨论两种方法。一种是嵌套Try...Catch 块。但我会推荐第二个,我将在下面详细介绍。

      我的假设是,如果您指定的调用成功,dir 将有一个值,如果没有,它将是Nothing。如果是这种情况,您可以有选择地执行您的异常处理程序,如下所示:

      Try
          dir = Directory.CreateDirectory(Path.Combine(My.Settings.CalibrationExcelExportPath, dirName))
          ' Other code here that might throw the same exception.
      Catch ex As IOException When dir Is Nothing
          ' Do what you need when the call to CreateDirectory has failed.
      Catch ex As IOException When dir Is Not Nothing
          ' For the other one. You can leave the when out in this instance
      Catch ex As Exception
          ' You still need to handle others that might come up.
      End Try
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-11
        • 2013-05-09
        • 2011-11-10
        • 1970-01-01
        • 2013-04-22
        • 1970-01-01
        相关资源
        最近更新 更多