2017-07-27 152 views
2

如果我调用两个可以抛出相同异常的方法,但异常的理由不同,应该如何处理?异常处理最佳实践

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

作为例子: 我有这样的方法

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

的方法,可以抛出IOexception

接下来我打电话给方法ExcelExport.ExportCalibrationAsync创建一个TempFile,如果没有更多的临时名称空闲,它也可以抛出IOexception

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

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

这里最好的做法是什么

回答

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 
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