C# Exception classes
In this chapter you will learn:
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:
- What are C# try Statements and Exceptions
- Syntax for try statement
- Example for try statement
- Use a nested try block