これは、 "throw" と "throw ex" に違いはありますか?</a>に対するフォローアップの質問です。
スタック トレースをリセットせずに新しいエラー処理メソッドを抽出する方法はありますか?
[編集] 「内部メソッド」とEarwickerが提供する別の回答の両方を試して、どちらが回答をマークするのに適しているかを確認します。
With .NET Framework 4.5 there is now an ExceptionDispatchInfo which supports this exact scenario. It allows capturing a complete exception and rethrowing it from somewhere else without overwriting the contained stack trace.
code sample due to request in comment
using System.Runtime.ExceptionServices;
class Test
{
private ExceptionDispatchInfo _exInfo;
public void DeleteNoThrow(string path)
{
try { File.Delete(path); }
catch(IOException ex)
{
// Capture exception (including stack trace) for later rethrow.
_exInfo = ExceptionDispatchInfo.Capture(ex);
}
}
public Exception GetFailure()
{
// You can access the captured exception without rethrowing.
return _exInfo != null ? _exInfo.SourceException : null;
}
public void ThrowIfFailed()
{
// This will rethrow the exception including the stack trace of the
// original DeleteNoThrow call.
_exInfo.Throw();
// Contrast with 'throw GetFailure()' which rethrows the exception but
// overwrites the stack trace to the current caller of ThrowIfFailed.
}
}
はい; それが InnerException プロパティの目的です。
catch(Exception ex)
{
throw new YourExceptionClass("message", ex);
}
これにより、独自のロジックを追加してから、独自の例外クラスをスローできます。YourExceptionClass インスタンスの StackTrace はこのコード ブロック内から取得されますが、InnerException は以前の StackTrace を使用してキャッチした例外になります。
あなたがそれを意味しているかどうかはわかりませんが、あなたの他の質問での私の提案はこれに対処することでした.
例外が処理されたかどうかにかかわらず、ハンドラーがブール値を返す場合は、これを catch 句で使用できます。
catch (Exception ex) {
if (!HandleException(ex)) {
throw;
}
}
元のスタック トレースを使用して新しい例外を作成する必要はありません。そのスタック トレースは新しい例外を作成しなかったため、誤解を招く可能性があります。
ただし、元の例外を新しい例外に「InnerException」として入れることはできます。それはあなたが探していることをしますか?