this other questionで説明したように、自分で投げる場合を除き、スタックオーバーフローの例外を実際に捕まえることはできません。
あなたの問題(実際には解決策ではありません)の回避策として、スタックオーバーフローを検出するコードをメソッド呼び出しに挿入して、手動で例外をスローして後でキャッチすることができます。
[TestClass]
public class TestStackOverflowDetection
{
[TestMethod]
public void TestDetectStackOverflow()
{
try
{
InfiniteRecursion();
}
catch (StackOverflowException e)
{
Debug.WriteLine(e);
}
}
private static int InfiniteRecursion(int i = 0)
{
// Insert the following call in all methods that
// we suspect could be part of an infinite recursion
CheckForStackOverflow();
// Force an infinite recursion
var j = InfiniteRecursion(i) + 1;
return j;
}
private static void CheckForStackOverflow()
{
var stack = new System.Diagnostics.StackTrace(true);
if (stack.FrameCount > 1000) // Set stack limit to 1,000 calls
{
// Output last 10 frames in the stack
foreach (var f in stack.GetFrames().Reverse().Take(30).Reverse())
Debug.Write("\tat " + f);
// Throw a stack overflow exception
throw new StackOverflowException();
}
}
例外を切り詰めているものがわかりません。時計や中間ウィンドウで 'new System.Diagnostics.StackTrace(true)'を使って独自のスタックトレースを作成してみることができますか?多分、これは完全なトレースを提供します。 – Caramiriel
@Caramirielインタラクティブにデバッグしている間に '現在のスレッドがスタックオーバーフロー状態にあるため式を評価できません。 'というメッセージが表示され、プロセスがその時点で実際に実行されていないため、クラッシュダンプをデバッグする際に直接式を実行できません。大量のスタックトレースは表示されません。 – Justin
@ジャスティン:あなたのビジュアルスタジオアーキテクチャ(例えばx86)があなたのアプリケーションに合っているならば、SOSをロードして、即時ウィンドウに '!clrstack'とタイプしてスタックトレースをダンプすることもできます。私のために働いているようだ。 ( '0028ed6c 00340147 ConsoleApplication45.Program.Rec()0028edac 003400fb ConsoleApplication45.Program.Main(System.String []) ') – Caramiriel