C# Exception classes

In this chapter you will learn:

  1. Predefined Exception classes
  2. Example for C# Exception

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; /*ww w .  ja va 2 s  .c  o 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.

Next chapter...

What you will learn in the next chapter:

  1. What are C# try Statements and Exceptions
  2. Syntax for try statement
  3. Example for try statement
  4. Use a nested try block
Home »
  C# Tutorial »
    C# Language »
      C# Exception
C# Exception
C# Exception classes
C# try Statements and Exceptions
C# catch Clause
C# finally Block
C# throw statement
C# System Exception