2017-07-27 150 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