C# Exception classes

Description

The following properties are defined in Exception.

  • Message property contains a string that describes the nature of the error.
  • StackTrace property contains a string that contains the stack of calls that lead to the exception.
  • TargetSite property obtains an object that specifies the method that generated the exception.

System.Exception also defines several methods.

  • ToString() returns a string that describes the exception.
  • Exception defines four constructors.

The most commonly used constructors are shown here:


Exception()
Exception(string str) 

Example

Example for C# Exception


using System; // w  w  w  .  j  a  v a 2  s  . co m
 
class MainClass {  
  public static void Main() {  
  
    try {  
        int[] nums = new int[4];  
     
        Console.WriteLine("Before exception is generated."); 
     
        // Generate an index out-of-bounds exception. 
        for(int i=0; i < 10; i++) { 
            nums[i] = i; 
        } 
    }  
    catch (IndexOutOfRangeException exc) {  
      Console.WriteLine("Standard message is: "); 
      Console.WriteLine(exc); // calls ToString() 
      Console.WriteLine("Stack trace: " + exc.StackTrace); 
      Console.WriteLine("Message: " + exc.Message); 
      Console.WriteLine("TargetSite: " + exc.TargetSite); 
      Console.WriteLine("Class defining member: {0}", exc.TargetSite.DeclaringType);
      Console.WriteLine("Member type: {0}", exc.TargetSite.MemberType);
      Console.WriteLine("Source: {0}", exc.Source);
      Console.WriteLine("Help Link: {0}", exc.HelpLink);
      
    }  
    Console.WriteLine("After catch statement.");  
  }  
}

The code above generates the following result.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception