Professional Documents
Culture Documents
using System;
class MainClass{
int Zero = 0;
try {
int j = 22 / Zero;
System.Exception.
hierarchies.
1. Message property contains a string that describes the nature of the error.
2. StackTrace property contains a string that contains the stack of calls that lead to the exception.
3. TargetSite property obtains an object that specifies the method that generated the exception.
System.Exception also defines several methods.
1. ToString() returns a string that describes the exception.
using System;
class MainClass {
public static void Main() {
try {
int[] nums = new int[4];
}
Console.WriteLine("After catch statement.");
}
}
using System;
class MainClass
{
public static void Main()
{
Console.WriteLine("Calling AccessInvalidArrayElement()");
AccessInvalidArrayElement();
try
{
Console.WriteLine("Calling DivideByZero()");
DivideByZero();
} catch (DivideByZeroException e) {
Console.WriteLine("Handling an IndexOutOfRangeException");
Console.WriteLine("Message = " + e.Message);
Console.WriteLine("StackTrace = " + e.StackTrace);
}
}
public static void AccessInvalidArrayElement()
{
int[] myArray = new int[2];
try
{
Console.WriteLine("Attempting to access an invalid array element");
myArray[20] = 1;
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("Handling an IndexOutOfRangeException");
Console.WriteLine("Message = " + e.Message);
Console.WriteLine("StackTrace = " + e.StackTrace);
}
}
Calling AccessInvalidArrayElement()
Attempting to access an invalid array element
Handling an IndexOutOfRangeException
Message = Index was outside the bounds of the array.
StackTrace = at MainClass.AccessInvalidArrayElement()
Calling DivideByZero()
Attempting division by zero
Handling an IndexOutOfRangeException
Message = Attempted to divide by zero.
StackTrace = at MainClass.Main()
Commonly Used Exceptions Defined Within the System Namespace
Exception Meaning
ArrayTypeMismatchExceptio
Type is incompatible with the type of the array.
n
DivideByZeroException Division by zero attempted.
IndexOutOfRangeException Array index is out of bounds.
InvalidCastException A runtime cast is invalid.
OutOfMemoryException Insufficient free memory exists.
OverflowException An arithmetic overflow occurred.
An attempt was made to operate on a null reference?that is,
NullReferenceException
a reference that does not refer to an object.
StackOverflowException The stack was Overflow.
As a general rule, exceptions defined by you should be derived from
ApplicationException since this is the
hierarchy reserved for application- related exceptions.