スタックトレース
スタックトレースとは、プログラムの実行過程を記録したスタックフレームを記録しておくことである。
スタックフレームは、関数が呼ばれるために生成される。その内容はシステムやコンパイラなどの実装によって異なるが、呼び出し元への戻りアドレスやローカル変数などによって構成されている。
スタックトレースでは、プログラムのデバック時に実行過程をプレイバックするための情報として活用でできる。関数名の情報さえあれば、スタックトレースから問題発生時に最後に実行していた関数名がわかる。また、プログラムが異常動作の結果により停止した場合には、スタックトレースにより、想定外の関数が動作していたことや、思わぬルートを実行されていたことなどが分かる場合があり、問題解決の重要な手がかりになる。
開発環境: | シンボリックデバッガ 条件コンパイル シングルステップ実行 スタックトレース デバッガ デバッグ トレース |
StackTrace クラス
アセンブリ: mscorlib (mscorlib.dll 内)


StackTrace 情報は、デバッグ ビルド構成と共に使用すると最も有益な情報となります。既定では、デバッグ ビルドにはデバッグ シンボルが含まれ、リリース ビルドには含まれません。デバッグ シンボルには、StackFrame オブジェクトおよび StackTrace オブジェクトを構築するために使用されるファイル、メソッド名、行番号、および列情報のほとんどが含まれます。
StackTrace では、最適化処理中に実行されたコード変換が原因で、予期したほど多くのメソッド呼び出しが報告されない場合があります。

単純な StackTrace を作成し、そのフレームを反復処理してデバッグ情報と診断情報を取得する方法を次のコンソール アプリケーションで示します。
Imports System Imports System.Diagnostics Class StackTraceSample <STAThread()> _ Public Shared Sub Main() Dim sample As New StackTraceSample() Try sample.MyPublicMethod() Catch ' Create a StackTrace that captures ' filename, line number, and column ' information for the current thread. Dim st As New StackTrace(True) Dim i As Integer For i = 0 To st.FrameCount - 1 ' Note that high up the call stack, there is only ' one stack frame. Dim sf As StackFrame = st.GetFrame(i) Console.WriteLine() Console.WriteLine("High up the call stack, Method: {0}", _ sf.GetMethod()) Console.WriteLine("High up the call stack, Line Number: {0}", _ sf.GetFileLineNumber()) Next i End Try End Sub Public Sub MyPublicMethod() MyProtectedMethod() End Sub Protected Sub MyProtectedMethod() Dim mic As New MyInternalClass() mic.ThrowsException() End Sub Class MyInternalClass Public Sub ThrowsException() Try Throw New Exception("A problem was encountered.") Catch e As Exception ' Create a StackTrace that captures filename, ' line number and column information. Dim st As New StackTrace(True) Dim stackIndent As String = "" Dim i As Integer For i = 0 To st.FrameCount - 1 ' Note that at this level, there are four ' stack frames, one for each method invocation. Dim sf As StackFrame = st.GetFrame(i) Console.WriteLine() Console.WriteLine(stackIndent + " Method: {0}", _ sf.GetMethod()) Console.WriteLine(stackIndent + " File: {0}", _ sf.GetFileName()) Console.WriteLine(stackIndent + " Line Number: {0}", _ sf.GetFileLineNumber()) stackIndent += " " Next i Throw e End Try End Sub End Class End Class ' This console application produces the following output when ' compiled with the Debug configuration. ' ' Method: Void ThrowsException() ' File: c:\pp\samples\stacktraceframe\myclass.vb ' Line Number: 55 ' ' Method: Void MyProtectedMethod() ' File: c:\pp\samples\stacktraceframe\myclass.vb ' Line Number: 42 ' ' Method: Void MyPublicMethod() ' File: c:\pp\samples\stacktraceframe\myclass.vb ' Line Number: 37 ' ' Method: Void Main(System.String[]) ' File: c:\pp\samples\stacktraceframe\myclass.vb ' Line Number: 13 ' ' High up the call stack, Method: Void Main(System.String[]) ' High up the call stack, Line Number: 18 ' ' ' This console application produces the following output when ' compiled with the Release configuration. ' ' Method: Void ThrowsException() ' File: ' Line Number: 0 ' ' Method: Void Main(System.String[]) ' File: ' Line Number: 0 ' ' High up the call stack, Method: Void Main() ' High up the call stack, Line Number: 0 '
using System; using System.Diagnostics; class StackTraceSample { [STAThread] static void Main(string[] args) { StackTraceSample sample = new StackTraceSample(); try { sample.MyPublicMethod(); } catch (Exception) { // Create a StackTrace that captures // filename, line number, and column // information for the current thread. StackTrace st = new StackTrace(true); for(int i =0; i< st.FrameCount; i++ ) { // Note that high up the call stack, there is only // one stack frame. StackFrame sf = st.GetFrame(i); Console.WriteLine(); Console.WriteLine("High up the call stack, Method: {0}" , sf.GetMethod()); Console.WriteLine("High up the call stack, Line Number: {0}" , sf.GetFileLineNumber()); } } } public void MyPublicMethod () { MyProtectedMethod(); } protected void MyProtectedMethod () { MyInternalClass mic = new MyInternalClass(); mic.ThrowsException(); } class MyInternalClass { public void ThrowsException() { try { throw new Exception("A problem was encountered."); } catch (Exception e) { // Create a StackTrace that captures filename, // line number and column information. StackTrace st = new StackTrace(true); string stackIndent = ""; for(int i =0; i< st.FrameCount; i++ ) { // Note that at this level, there are four // stack frames, one for each method invocation. StackFrame sf = st.GetFrame(i); Console.WriteLine(); Console.WriteLine(stackIndent + " Method: {0}", sf.GetMethod() ); Console.WriteLine( stackIndent + " File: {0}", sf.GetFileName()); Console.WriteLine( stackIndent + " Line Number: {0}" , sf.GetFileLineNumber()); stackIndent += " "; } throw e; } } } } /* This console application produces the following output when compiled with the Debug configuration. Method: Void ThrowsException() File: c:\samples\stacktraceframe\myclass.cs Line Number: 59 Method: Void MyProtectedMethod() File: c:\samples\stacktraceframe\myclass.cs Line Number: 45 Method: Void MyPublicMethod() File: c:\samples\stacktraceframe\myclass.cs Line Number: 39 Method: Void Main(System.String[]) File: c:\samples\stacktraceframe\myclass.cs Line Number: 13 High up the call stack, Method: Void Main(System.String[]) High up the call stack, Line Number: 20 This console application produces the following output when compiled with the Release configuration. Method: Void ThrowsException() File: Line Number: 0 Method: Void Main(System.String[]) File: Line Number: 0 High up the call stack, Method: Void Main(System.String[]) High up the call stack, Line Number: 0 */
#using <System.dll> using namespace System; using namespace System::Diagnostics; ref class StackTraceSample { private: ref class MyInternalClass { public: void ThrowsException() { try { throw gcnew Exception( "A problem was encountered." ); } catch ( Exception^ e ) { // Create a StackTrace that captures // filename, line number, and column // information for the current thread. StackTrace^ st = gcnew StackTrace( true ); String^ stackIndent = ""; for ( int i = 0; i < st->FrameCount; i++ ) { // Note that at this level, there are five // stack frames, one for each method invocation. StackFrame^ sf = st->GetFrame( i ); Console::WriteLine(); Console::WriteLine( "{0}Method: {1}", stackIndent, sf->GetMethod() ); Console::WriteLine( "{0}File: {1}", stackIndent, sf->GetFileName() ); Console::WriteLine( "{0}Line Number: {1}", stackIndent, sf->GetFileLineNumber().ToString() ); stackIndent = String::Concat( stackIndent, " " ); } throw e; } } }; protected: void MyProtectedMethod() { MyInternalClass^ mic = gcnew MyInternalClass; mic->ThrowsException(); } public: void MyPublicMethod() { MyProtectedMethod(); } }; int main() { StackTraceSample^ sample = gcnew StackTraceSample; try { sample->MyPublicMethod(); } catch ( Exception^ ) { // Create a StackTrace that captures // filename, line number, and column // information for the current thread. StackTrace^ st = gcnew StackTrace( true ); for ( int i = 0; i < st->FrameCount; i++ ) { // For an executable built from C++, there // are two stack frames here: one for main, // and one for the _mainCRTStartup stub. StackFrame^ sf = st->GetFrame( i ); Console::WriteLine(); Console::WriteLine( "High up the call stack, Method: {0}", sf->GetMethod()->ToString() ); Console::WriteLine( "High up the call stack, Line Number: {0}", sf->GetFileLineNumber().ToString() ); } } } /* This console application produces the following output when compiled with the Debug configuration. Method: Void ThrowsException() File: c:\samples\stacktraceframe\myclass.cpp Line Number: 20 Method: Void MyProtectedMethod() File: c:\samples\stacktraceframe\myclass.cpp Line Number: 45 Method: Void MyPublicMethod() File: c:\samples\stacktraceframe\myclass.cpp Line Number: 50 Method: Int32 main() File: c:\samples\stacktraceframe\myclass.cpp Line Number: 56 Method: UInt32 _mainCRTStartup() File: Line Number: 0 High up the call stack, Method: Int32 main() High up the call stack, Line Number: 62 High up the call stack, Method: UInt32 _mainCRTStartup() High up the call stack, Line Number: 0 This console application produces the following output when compiled with the Release configuration. Method: Void ThrowsException() File: Line Number: 0 Method: Int32 main() File: Line Number: 0 Method: UInt32 _mainCRTStartup() File: Line Number: 0 High up the call stack, Method: Int32 main() High up the call stack, Line Number: 0 High up the call stack, Method: UInt32 _mainCRTStartup() High up the call stack, Line Number: 0 */
import System.*; import System.Diagnostics.*; class StackTraceSample { /** @attribute STAThread() */ public static void main(String[] args) { StackTraceSample sample = new StackTraceSample(); try { sample.MyPublicMethod(); } catch (System.Exception exp) { // Create a StackTrace that captures // filename, line number, and column // information for the current thread. StackTrace st = new StackTrace(true); for (int i = 0; i < st.get_FrameCount(); i++) { // Note that high up the call stack, there is only // one stack frame. StackFrame sf = st.GetFrame(i); Console.WriteLine(); Console.WriteLine("High up the call stack, Method: {0}" , sf.GetMethod()); Console.WriteLine("High up the call stack, Line Number: {0}" , (Int32)sf.GetFileLineNumber()); } } } //main public void MyPublicMethod() throws System.Exception { MyProtectedMethod(); } //MyPublicMethod protected void MyProtectedMethod() throws System.Exception { MyInternalClass mic = new MyInternalClass(); mic.ThrowsException(); } //MyProtectedMethod class MyInternalClass { public void ThrowsException() throws System.Exception { try { throw new System.Exception("A problem was encountered."); } catch (System.Exception e) { // Create a StackTrace that captures filename, // line number and column information. StackTrace st = new StackTrace(true); String stackIndent = ""; for (int i = 0; i < st.get_FrameCount(); i++) { // Note that at this level, there are four // stack frames, one for each method invocation. StackFrame sf = st.GetFrame(i); Console.WriteLine(); Console.WriteLine(stackIndent + " Method: {0}", sf.GetMethod()); Console.WriteLine(stackIndent + " File: {0}", sf.GetFileName()); Console.WriteLine(stackIndent + " Line Number: {0}", (Int32)sf.GetFileLineNumber()); stackIndent += " "; } throw e; } } //ThrowsException } //MyInternalClass } //StackTraceSample /* This console application produces the following output when compiled with the Debug configuration. Method: Void ThrowsException() File: c:\samples\stacktraceframe\myclass.jsl Line Number: 57 Method: Void MyProtectedMethod() File: c:\samples\stacktraceframe\myclass.jsl Line Number: 43 Method: Void MyPublicMethod() File: c:\samples\stacktraceframe\myclass.jsl Line Number: 37 Method: Void main(System.String[]) File: c:\samples\stacktraceframe\myclass.jsl Line Number: 14 High up the call stack, Method: Void main(System.String[]) High up the call stack, Line Number: 21 This console application produces the following output when compiled with the Release configuration. Method: Void ThrowsException() File: Line Number: 0 Method: Void MyProtectedMethod() File: Line Number: 0 Method: Void MyPublicMethod() File: Line Number: 0 Method: Void main(System.String[]) File: Line Number: 0 High up the call stack, Method: Void main(System.String[]) High up the call stack, Line Number: 0 */

System.Diagnostics.StackTrace


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


StackTrace メンバ
System.Diagnostics 名前空間
Exception.StackTrace
Environment.StackTrace
ServerFault.StackTrace
StackTrace コンストラクタ ()
アセンブリ: mscorlib (mscorlib.dll 内)


StackTrace は、呼び出し元の現在のスレッドで作成され、ファイル名、行番号、および列情報を含みません。
コール スタックに関するメソッドの概要情報だけを持つ完全なトレースが必要な場合は、この既定のコンストラクタを使用します。

スタック トレース内の最初と最後の関数呼び出しを表示するコード例を次に示します。
Public Sub Level5Method() Try Dim nestedClass As New ClassLevel6() nestedClass.Level6Method() Catch e As Exception Console.WriteLine(" Level5Method exception handler") Dim st As New StackTrace() ' Display the most recent function call. Dim sf As StackFrame = st.GetFrame(0) Console.WriteLine() Console.WriteLine(" Exception in method: ") Console.WriteLine(" {0}", sf.GetMethod()) If st.FrameCount > 1 Then ' Display the highest-level function call in the trace. sf = st.GetFrame((st.FrameCount - 1)) Console.WriteLine(" Original function call at top of call stack):") Console.WriteLine(" {0}", sf.GetMethod()) End If Console.WriteLine() Console.WriteLine(" ... throwing exception to next level ...") Console.WriteLine("-------------------------------------------------") Console.WriteLine() Throw e End Try End Sub 'Level5Method
public void Level5Method() { try { ClassLevel6 nestedClass = new ClassLevel6(); nestedClass.Level6Method(); } catch (Exception e) { Console.WriteLine(" Level5Method exception handler"); StackTrace st = new StackTrace(); // Display the most recent function call. StackFrame sf = st.GetFrame(0); Console.WriteLine(); Console.WriteLine(" Exception in method: "); Console.WriteLine(" {0}", sf.GetMethod()); if (st.FrameCount >1) { // Display the highest-level function call // in the trace. sf = st.GetFrame(st.FrameCount-1); Console.WriteLine(" Original function call at top of call stack):"); Console.WriteLine(" {0}", sf.GetMethod()); } Console.WriteLine(); Console.WriteLine(" ... throwing exception to next level ..."); Console.WriteLine("-------------------------------------------------\n"); throw e; } }
void Level5Method() { try { ClassLevel6^ nestedClass = gcnew ClassLevel6; nestedClass->Level6Method(); } catch ( Exception^ e ) { Console::WriteLine( " Level5Method exception handler" ); StackTrace^ st = gcnew StackTrace; // Display the most recent function call. StackFrame^ sf = st->GetFrame( 0 ); Console::WriteLine(); Console::WriteLine( " Exception in method: " ); Console::WriteLine( " {0}", sf->GetMethod() ); if ( st->FrameCount > 1 ) { // Display the highest-level function call // in the trace. sf = st->GetFrame( st->FrameCount - 1 ); Console::WriteLine( " Original function call at top of call stack):" ); Console::WriteLine( " {0}", sf->GetMethod() ); } Console::WriteLine(); Console::WriteLine( " ... throwing exception to next level ..." ); Console::WriteLine( "-------------------------------------------------\n" ); throw e; } }
public void Level5Method() throws System.Exception { try { ClassLevel6 nestedClass = new ClassLevel6(); nestedClass.Level6Method(); } catch (System.Exception e) { Console.WriteLine(" Level5Method exception handler"); StackTrace st = new StackTrace(); // Display the most recent function call. StackFrame sf = st.GetFrame(0); Console.WriteLine(); Console.WriteLine(" Exception in method: "); Console.WriteLine(" {0}", sf.GetMethod()); if (st.get_FrameCount() > 1) { // Display the highest-level function call // in the trace. sf = st.GetFrame(st.get_FrameCount() - 1); Console.WriteLine(" Original function call at top of call " + "stack):"); Console.WriteLine(" {0}", sf.GetMethod()); } Console.WriteLine(); Console.WriteLine(" ... throwing exception to next level..."); Console.WriteLine("--------------------------------------------" + "-----\n"); throw e; } } //Level5Method

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


StackTrace コンストラクタ (Exception)
アセンブリ: mscorlib (mscorlib.dll 内)




Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


StackTrace コンストラクタ (StackFrame)
アセンブリ: mscorlib (mscorlib.dll 内)



スタック トレース情報をイベント ログ エントリに書き込むコード例を次に示します。
Dim frame As New StackFrame(1, True) Dim strace As New StackTrace(frame) EventLog.WriteEntry(frame.GetMethod().Name, _ strace.ToString(), _ EventLogEntryType.Warning)
StackFrame fr = new StackFrame(1,true); StackTrace st = new StackTrace(fr); EventLog.WriteEntry(fr.GetMethod().Name, st.ToString(), EventLogEntryType.Warning);

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


StackTrace コンストラクタ (Boolean)
アセンブリ: mscorlib (mscorlib.dll 内)



さまざまな StackTrace コンストラクタ メソッドのコード例を次に示します。
Public Sub Level2Method() Try Dim nestedClass As New ClassLevel3 nestedClass.Level3Method() Catch e As Exception Console.WriteLine(" Level2Method exception handler") ' Display the full call stack at this level. Dim st1 As New StackTrace(True) Console.WriteLine(" Stack trace for this level: {0}", _ st1.ToString()) ' Build a stack trace from one frame, skipping the current ' frame and using the next frame. Dim st2 As New StackTrace(New StackFrame(1, True)) Console.WriteLine(" Stack trace built with next level frame: {0}", _ st2.ToString()) ' Build a stack trace skipping the current frame, and ' including all the other frames. Dim st3 As New StackTrace(1, True) Console.WriteLine(" Stack trace built from the next level up: {0}", _ st3.ToString()) Console.WriteLine() Console.WriteLine(" ... throwing exception to next level ...") Console.WriteLine("-------------------------------------------------") Console.WriteLine() Throw e End Try End Sub 'Level2Method
public void Level2Method() { try { ClassLevel3 nestedClass = new ClassLevel3(); nestedClass.Level3Method(); } catch (Exception e) { Console.WriteLine(" Level2Method exception handler"); // Display the full call stack at this level. StackTrace st1 = new StackTrace(true); Console.WriteLine(" Stack trace for this level: {0}", st1.ToString()); // Build a stack trace from one frame, skipping the current // frame and using the next frame. StackTrace st2 = new StackTrace(new StackFrame(1, true)); Console.WriteLine(" Stack trace built with next level frame: {0}" , st2.ToString()); // Build a stack trace skipping the current frame, and // including all the other frames. StackTrace st3 = new StackTrace(1, true); Console.WriteLine(" Stack trace built from the next level up: {0}" , st3.ToString()); Console.WriteLine(); Console.WriteLine(" ... throwing exception to next level ..."); Console.WriteLine("-------------------------------------------------\n"); throw e; } }
void Level2Method() { try { ClassLevel3^ nestedClass = gcnew ClassLevel3; nestedClass->Level3Method(); } catch ( Exception^ e ) { Console::WriteLine( " Level2Method exception handler" ); // Display the full call stack at this level. StackTrace^ st1 = gcnew StackTrace( true ); Console::WriteLine( " Stack trace for this level: {0}", st1->ToString() ); // Build a stack trace from one frame, skipping the // current frame and using the next frame. StackTrace^ st2 = gcnew StackTrace( gcnew StackFrame( 1,true ) ); Console::WriteLine( " Stack trace built with next level frame: {0}", st2->ToString() ); // Build a stack trace skipping the current frame, and // including all the other frames. StackTrace^ st3 = gcnew StackTrace( 1,true ); Console::WriteLine( " Stack trace built from the next level up: {0}", st3->ToString() ); Console::WriteLine(); Console::WriteLine( " ... throwing exception to next level ..." ); Console::WriteLine( "-------------------------------------------------\n" ); throw e; } }
public void Level2Method() throws System.Exception { try { ClassLevel3 nestedClass = new ClassLevel3(); nestedClass.Level3Method(); } catch (System.Exception e) { Console.WriteLine(" Level2Method exception handler"); // Display the full call stack at this level. StackTrace st1 = new StackTrace(true); Console.WriteLine(" Stack trace for this level: {0}", st1.ToString()); // Build a stack trace from one frame, skipping the current // frame and using the next frame. StackTrace st2 = new StackTrace(new StackFrame(1, true)); Console.WriteLine(" Stack trace built with next level frame: {0}" , st2.ToString()); // Build a stack trace skipping the current frame, and // including all the other frames. StackTrace st3 = new StackTrace(1, true); Console.WriteLine(" Stack trace built from the next level up: {0}" , st3.ToString()); Console.WriteLine(); Console.WriteLine(" ... throwing exception to next level..."); Console.WriteLine("--------------------------------------------" + "-----\n"); throw e; } } //Level2Method

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


StackTrace コンストラクタ (Exception, Int32, Boolean)
アセンブリ: mscorlib (mscorlib.dll 内)

Dim e As Exception Dim skipFrames As Integer Dim fNeedFileInfo As Boolean Dim instance As New StackTrace(e, skipFrames, fNeedFileInfo)


結果として得られるスタック トレースは、例外が発生した時点のスタックを説明します。
インスタンスの作成時に、スキップするフレームの数がコール スタック上のフレームの合計数以上の場合は、StackTrace にフレームは含まれません。

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


StackTrace コンストラクタ (Exception, Boolean)
アセンブリ: mscorlib (mscorlib.dll 内)




Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


StackTrace コンストラクタ (Int32, Boolean)
アセンブリ: mscorlib (mscorlib.dll 内)

Dim skipFrames As Integer Dim fNeedFileInfo As Boolean Dim instance As New StackTrace(skipFrames, fNeedFileInfo)



さまざまな StackTrace コンストラクタ メソッドのコード例を次に示します。
Public Sub Level2Method() Try Dim nestedClass As New ClassLevel3 nestedClass.Level3Method() Catch e As Exception Console.WriteLine(" Level2Method exception handler") ' Display the full call stack at this level. Dim st1 As New StackTrace(True) Console.WriteLine(" Stack trace for this level: {0}", _ st1.ToString()) ' Build a stack trace from one frame, skipping the current ' frame and using the next frame. Dim st2 As New StackTrace(New StackFrame(1, True)) Console.WriteLine(" Stack trace built with next level frame: {0}", _ st2.ToString()) ' Build a stack trace skipping the current frame, and ' including all the other frames. Dim st3 As New StackTrace(1, True) Console.WriteLine(" Stack trace built from the next level up: {0}", _ st3.ToString()) Console.WriteLine() Console.WriteLine(" ... throwing exception to next level ...") Console.WriteLine("-------------------------------------------------") Console.WriteLine() Throw e End Try End Sub 'Level2Method
public void Level2Method() { try { ClassLevel3 nestedClass = new ClassLevel3(); nestedClass.Level3Method(); } catch (Exception e) { Console.WriteLine(" Level2Method exception handler"); // Display the full call stack at this level. StackTrace st1 = new StackTrace(true); Console.WriteLine(" Stack trace for this level: {0}", st1.ToString()); // Build a stack trace from one frame, skipping the current // frame and using the next frame. StackTrace st2 = new StackTrace(new StackFrame(1, true)); Console.WriteLine(" Stack trace built with next level frame: {0}" , st2.ToString()); // Build a stack trace skipping the current frame, and // including all the other frames. StackTrace st3 = new StackTrace(1, true); Console.WriteLine(" Stack trace built from the next level up: {0}" , st3.ToString()); Console.WriteLine(); Console.WriteLine(" ... throwing exception to next level ..."); Console.WriteLine("-------------------------------------------------\n"); throw e; } }
void Level2Method() { try { ClassLevel3^ nestedClass = gcnew ClassLevel3; nestedClass->Level3Method(); } catch ( Exception^ e ) { Console::WriteLine( " Level2Method exception handler" ); // Display the full call stack at this level. StackTrace^ st1 = gcnew StackTrace( true ); Console::WriteLine( " Stack trace for this level: {0}", st1->ToString() ); // Build a stack trace from one frame, skipping the // current frame and using the next frame. StackTrace^ st2 = gcnew StackTrace( gcnew StackFrame( 1,true ) ); Console::WriteLine( " Stack trace built with next level frame: {0}", st2->ToString() ); // Build a stack trace skipping the current frame, and // including all the other frames. StackTrace^ st3 = gcnew StackTrace( 1,true ); Console::WriteLine( " Stack trace built from the next level up: {0}", st3->ToString() ); Console::WriteLine(); Console::WriteLine( " ... throwing exception to next level ..." ); Console::WriteLine( "-------------------------------------------------\n" ); throw e; } }
public void Level2Method() throws System.Exception { try { ClassLevel3 nestedClass = new ClassLevel3(); nestedClass.Level3Method(); } catch (System.Exception e) { Console.WriteLine(" Level2Method exception handler"); // Display the full call stack at this level. StackTrace st1 = new StackTrace(true); Console.WriteLine(" Stack trace for this level: {0}", st1.ToString()); // Build a stack trace from one frame, skipping the current // frame and using the next frame. StackTrace st2 = new StackTrace(new StackFrame(1, true)); Console.WriteLine(" Stack trace built with next level frame: {0}" , st2.ToString()); // Build a stack trace skipping the current frame, and // including all the other frames. StackTrace st3 = new StackTrace(1, true); Console.WriteLine(" Stack trace built from the next level up: {0}" , st3.ToString()); Console.WriteLine(); Console.WriteLine(" ... throwing exception to next level..."); Console.WriteLine("--------------------------------------------" + "-----\n"); throw e; } } //Level2Method

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


StackTrace コンストラクタ

名前 | 説明 |
---|---|
StackTrace () | StackTrace クラスの新しいインスタンスを呼び出し元のフレームから初期化します。 |
StackTrace (Boolean) | StackTrace クラスの新しいインスタンスを呼び出し元のフレームから初期化し、オプションでソース情報をキャプチャします。 |
StackTrace (Exception) | 指定した例外オブジェクトを使用して、StackTrace クラスの新しいインスタンスを初期化します。 |
StackTrace (Int32) | 呼び出し元のフレームから StackTrace クラスの新しいインスタンスを初期化し、指定した数のフレームをスキップします。 |
StackTrace (StackFrame) | 単一フレームを格納している StackTrace クラスの新しいインスタンスを初期化します。 |
StackTrace (Exception, Boolean) | 指定した例外オブジェクトを使用して StackTrace クラスの新しいインスタンスを初期化し、オプションでソース情報をキャプチャします。 |
StackTrace (Exception, Int32) | 指定した例外オブジェクトを使用して StackTrace クラスの新しいインスタンスを初期化し、指定した数のフレームをスキップします。 |
StackTrace (Int32, Boolean) | 呼び出し元のフレームから StackTrace クラスの新しいインスタンスを初期化し、指定した数のフレームをスキップしたり、必要に応じてソース情報を取得したりできます。 |
StackTrace (Thread, Boolean) | 指定したスレッド用に StackTrace クラスの新しいインスタンスを初期化し、オプションでソース情報をキャプチャします。 |
StackTrace (Exception, Int32, Boolean) | 指定した例外オブジェクトを使用して、StackTrace クラスの新しいインスタンスを初期化し、指定したフレーム数をスキップしたり、必要に応じてソース情報を取得したりできます。 |

StackTrace コンストラクタ (Thread, Boolean)
アセンブリ: mscorlib (mscorlib.dll 内)

Dim targetThread As Thread Dim needFileInfo As Boolean Dim instance As New StackTrace(targetThread, needFileInfo)



Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


StackTrace コンストラクタ (Exception, Int32)
アセンブリ: mscorlib (mscorlib.dll 内)



StackTrace は、ファイル名、行番号、または列情報を含みません。
結果として得られるスタック トレースは、例外が発生した時点のスタックを説明します。
インスタンスの作成時に、スキップするフレームの数がコール スタック上のフレームの合計数以上の場合は、StackTrace にフレームは含まれません。

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


StackTrace コンストラクタ (Int32)
アセンブリ: mscorlib (mscorlib.dll 内)



StackTrace は、呼び出し元の現在のスレッドで作成され、ファイル名、行番号、および列情報を含みません。
インスタンスの作成時に、スキップするフレームの数がコール スタック上のフレームの合計数以上の場合は、StackTrace にフレームは含まれません。

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


StackTrace フィールド


関連項目
StackTrace クラスSystem.Diagnostics 名前空間
Exception.StackTrace
Environment.StackTrace
ServerFault.StackTrace
StackTrace プロパティ


関連項目
StackTrace クラスSystem.Diagnostics 名前空間
Exception.StackTrace
Environment.StackTrace
ServerFault.StackTrace
StackTrace メソッド

名前 | 説明 | |
---|---|---|
![]() | Equals | オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。) |
![]() | GetFrame | 指定したスタック フレームを取得します。 |
![]() | GetFrames | 現在のスタック トレース内のすべてのスタック フレームのコピーを返します。 |
![]() | GetHashCode | 特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。) |
![]() | GetType | 現在のインスタンスの Type を取得します。 ( Object から継承されます。) |
![]() | ReferenceEquals | 指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。) |
![]() | ToString | オーバーライドされます。 スタック トレースの読み取り可能な形式を構築します。 |

名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 ( Object から継承されます。) |
![]() | MemberwiseClone | 現在の Object の簡易コピーを作成します。 ( Object から継承されます。) |

関連項目
StackTrace クラスSystem.Diagnostics 名前空間
Exception.StackTrace
Environment.StackTrace
ServerFault.StackTrace
StackTrace メンバ
スタック トレースを表します。スタック トレースは、順番に並べられた 1 つまたは複数のスタック フレームのコレクションです。
StackTrace データ型で公開されるメンバを以下の表に示します。




名前 | 説明 | |
---|---|---|
![]() | Equals | オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。) |
![]() | GetFrame | 指定したスタック フレームを取得します。 |
![]() | GetFrames | 現在のスタック トレース内のすべてのスタック フレームのコピーを返します。 |
![]() | GetHashCode | 特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。) |
![]() | GetType | 現在のインスタンスの Type を取得します。 (Object から継承されます。) |
![]() | ReferenceEquals | 指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。) |
![]() | ToString | オーバーライドされます。 スタック トレースの読み取り可能な形式を構築します。 |

名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 (Object から継承されます。) |
![]() | MemberwiseClone | 現在の Object の簡易コピーを作成します。 (Object から継承されます。) |

関連項目
StackTrace クラスSystem.Diagnostics 名前空間
Exception.StackTrace
Environment.StackTrace
ServerFault.StackTrace
スタックトレース
![]() | この記事は検証可能な参考文献や出典が全く示されていないか、不十分です。(2023年4月) |
コンピュータにおいて、スタックトレース(英語: stack trace)とは、プログラムの実行中の特定の時点でのアクティブなスタックフレームのレポートである。スタックバックトレース(英語: stack backtrace[1])、スタックトレースバック(英語: stack traceback[2])とも言い、単にバックトレースとも言う[注釈 1]。
詳細
プログラムが実行されると、多くの場合、スタックとヒープの2つの場所にメモリが動的に割り当てられる。スタックという用語はプログラム要素としての一般的なデータ構造のひとつについても使われるため、区別するために、このスタックはコールスタック (call stack) と呼ばれる。ヒープはプロセス内の全スレッドで共有されるが、コールスタックはスレッドごとに割り当てられる。技術的には、メモリブロックがいったんスタックに割り当てられると、その前に割り当てられていた他のメモリブロックが存在している可能性があるため、簡単に削除することはできない[注釈 2]。プログラムで関数(サブルーチン)が呼び出されるたびに、コールスタックの最上部にスタックフレーム(またはアクティベーションレコード)と呼ばれるメモリブロックが割り当てられる。スタックフレームは一般的に、関数宣言の仮引数に対応する値として関数に渡された実引数、関数内で定義されたローカル変数、関数終了時に復帰する位置を記憶するためのリターンアドレスなどを保持する[3]。
プログラマは通常、デバッグにおいてスタックトレースを使用する。一般的な統合開発環境では、デバッガをブレーク(一時停止)したときに「呼び出し履歴」としてスタックトレースを直感的に表示・追跡することができる[4]。エンドユーザには、エラーメッセージの一部としてスタックトレースが表示されることがあり、障害報告の際に活用することができる。
スタックトレースを使用すると、スタックトレースが生成されるまでの、呼び出された入れ子関数のシーケンスを追跡できる。事後分析では、障害が発生した関数まで追跡できる(ただし必ずしも追跡できるわけではない)。末尾再帰はスタックトレースに表示されない。
次の、エラーが含まれたPythonプログラムで説明する。
def a():
i = 0
j = b(i)
return j
def b(z):
k = 5
if z == 0:
c()
return k/z
def c():
error() #存在しない関数を呼び出そうとしている
a()
このプログラムを標準のPythonインタプリタで実行すると、次のエラーメッセージが生成される。
Traceback (most recent call last):
File "tb.py", line 15, in <module>
a()
File "tb.py", line 3, in a
j = b(i)
File "tb.py", line 9, in b
c()
File "tb.py", line 13, in c
error()
NameError: name 'error' is not defined
スタックトレースは、エラーが発生した場所、つまり関数c
を示している。また、関数c
は関数b
から、関数b
は関数a
から、関数a
はプログラムの15行目(最終行)から呼び出されたことも示している。
これらの3つの関数のそれぞれのアクティベーションレコードは、関数a
がスタックの下部を占有し、関数c
がスタックの上部を占有するようにスタックに配置される。
プログラミング言語によるサポート
JavaやC# (.NET) など多くのプログラミング言語には、システムコールを介して現在のスタックトレースを取得するための機能が標準クラスライブラリおよび実行環境に組み込まれている[5][6][7]。
C++にはスタックトレースを取得するための標準化された組み込みの機能はないが、Boost C++ライブラリのBoost.Stacktrace[8]、stacktraceライブラリ(2013年を最後に更新停止)などを使用してスタックトレースを取得できる。C++23ではBoost.Stacktraceをベースに標準化したサブセットとしてstd::stacktrace
が導入される予定である[9]。
JavaScriptでは、例外オブジェクトが、スローされた場所からのスタックを含むstack
プロパティを保持している。他にはconsole.trace()
メソッドを利用する方法もある[10]。
脚注
注釈
- ^ GNUデバッガ (gdb) でのレポートコマンドは、バックトレース (backtrace) を縮めた
bt
である。GNUデバッガ#コマンド例も参照。 - ^ コールスタックの割り当てと解放は通例オペレーティングシステムが担当し、アプリケーションプログラムで明示的に割り当てと解放をする必要はない。
出典
- ^ “libc manual: backtraces”. gnu.org. 2014年7月8日閲覧。
- ^ “traceback — Print or retrieve a stack traceback”. python.org. 2014年7月8日閲覧。
- ^ Examining the Stack Trace - Windows drivers | Microsoft Learn
- ^ デバッガーで呼び出し履歴を表示する - Visual Studio (Windows) | Microsoft Learn
- ^ Throwable (Java Platform SE 8 )
- ^ Environment.StackTrace Property (System) | Microsoft Learn
- ^ Exception.StackTrace Property (System) | Microsoft Learn
- ^ Chapter 35. Boost.Stacktrace 1.0 - 1.82.0
- ^ basic_stacktrace - cpprefjp C++日本語リファレンス
- ^ console.trace() - Web API | MDN
関連項目
「stack trace」の例文・使い方・用例・文例
- stack traceのページへのリンク