Sunday, 28 April 2013

Does the System.Exception class have any cool features? | C#.Net Interview Questions

Yes - the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from.
For example, the following code:
 using System;
 class CApp
 { 
  public static void Main()
  {
  try
 {
 f();
  }
 catch( Exception e )
 {
 Console.WriteLine("System.Exception stack trace=\n{0}", e.StackTrace );
 }
 }
 static void f()
 {
 throw new Exception( "f went pear-shaped" );
  }
  }
produces this output:
System.Exception stack trace =
at CApp.f()
at CApp.Main()
Note: however, that this stack trace was produced from a debug build. A release build may optimise away some of the method calls which could mean that the call stack isn't quite what you expect.

No comments: