异常处理最佳实践

时间:2017-07-27 11:00:24

标签: .net vb.net exception

如果我调用两个可以在彼此之后抛出相同异常的方法,但异常的基础是不同的,我应该如何处理它?<​​/ p>

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

例如: 我有这个方法

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

该方法可以抛出IOexception

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

现在我想在diff中处理异常。向用户提供适当信息的方式。

我已尝试使用exception.TargetSite,但我得到Void WinIOError(Int..)两次,所以我无法用它来区分。

这里的最佳做法是什么

2 个答案:

答案 0 :(得分:3)

我有两种方式可以谈论这样做。一种是嵌套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

答案 1 :(得分:2)

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

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创建您喜欢的处理程序。

相关问题