2017-07-27 26 views
2

同じ例外をスローする可能性があるが例外の根拠が異なる2つのメソッドを呼び出すと、どうすればよいでしょうか?例外処理のベストプラクティス

それぞれのメソッドの周りにtry catchブロックを置くと、別の方法で両方の例外を処理できるようにするか、例外をスローするメソッドをどのように取得できますか?一例として、

:私はこの方法

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

にメソッドを持っている がIOexceptionを投げることができます。

次の例では、テンポラリファイルを作成するメソッドExcelExport.ExportCalibrationAsyncを呼び出しています。テンポラリファイルの名前がない場合は、IOexceptionが返されます。

ここで、diffで例外を処理したいと考えています。ユーザーに適切な情報を提供する方法。

私はexception.TargetSiteで試しましたが、私は両方の時間がVoid WinIOError(Int..)になるので区別するために使用することはできません。

ここでのベストプラクティス

答えて

3

ここでは2つの方法で説明します。 1つはあなたのTry...Catchブロックをネストすることです。しかし、私は以下に詳述した2番目をお勧めします。

ここでは、指定した呼び出しが成功した場合は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

は、私はあなたのコールスタックが深いかもしれないので、あなたが、あなたのカスタム例外を作成することをお勧めし、あなたは異なる方法でハンドラを有することができます例外がどこから来たのかあなたはCreateDirectoryExceptionAnotherExceptionのために好きなハンドラの作成より

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