Csharp/CSharp Tutorial/Language Basics/Exception — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 15:31, 26 мая 2010

A Closer Look at Exception

  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.
  2. Exception defines four constructors.

The most commonly used are shown here:


Exception()
  Exception(string str)

An unhandled exception

using System;
class MainClass
{
  public static void Main()
  {
    int[] myArray = new int[2];
    Console.WriteLine("Attempting to access an invalid array element");
    myArray[2] = 1;
  }
}
Attempting to access an invalid array element
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at MainClass.Main()

Commonly Used Exceptions Defined Within the System Namespace

Exception Meaning ArrayTypeMismatchException Type is incompatible with the type of the array. 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. NullReferenceException An attempt was made to operate on a null reference�that is, 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.

Exception propagation with methods

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);
    }
  }
  public static void DivideByZero()
  {
    int zero = 0;
    Console.WriteLine("Attempting division by zero");
    int myInt = 1 / zero;
  }
}
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()

Handling a possible exception.

using System;
class MainClass {
    public static int AnExceptionFunction(int value) {
        if (value == 0) // Can"t divide by zero
            throw new DivideByZeroException("Divide By 0 error!");
        int x = 20 / value;
        return x;
    }
    public static void Main() {
        int value = 0;
        try {
            value = AnExceptionFunction(10); // This works ok
            Console.WriteLine("Value = {0}", value);
            AnExceptionFunction(0); // This doesn"t
            Console.WriteLine("Value = {0}", value);
        } catch (Exception e) {
            Console.WriteLine("Caught an exception {0}. Continuing", e);
        }
        Console.WriteLine("Done");
    }
}

The Exception Hierarchy

An exception is an error that occurs at runtime.


using System;
class MainClass{
    
    public static void Main(){
        int Zero = 0;
        try {
            int j = 22 / Zero;
        } catch (DivideByZeroException e) // catch a specific exception
        {
            Console.WriteLine("DivideByZero {0}", e);
        } catch (Exception e)// catch any remaining exceptions
        {
            Console.WriteLine("Exception {0}", e);
        }
    }
}
DivideByZero System.DivideByZeroException: Attempted to divide by zero.
   at MainClass.Main()

The System.Exception Class

  1. In C#, exceptions are represented by classes.
  2. All exception classes must be derived from the built-in exception class System.Exception.
  3. SystemException class and ApplicationException class are derived from System.Exception.
  4. SystemException support exceptions generated by the C# runtime system (that is, the Common Language Runtime)
  5. ApplicationException support exceptions generated by application programs.
  6. SystemException and ApplicationException add nothing to Exception.
  7. SystemException and ApplicationException define the tops of two different exception hierarchies.

1.17.Exception 1.17.1. <A href="/Tutorial/CSharp/0020__Language-Basics/TheExceptionHierarchy.htm">The Exception Hierarchy</a> 1.17.2. The System.Exception Class 1.17.3. <A href="/Tutorial/CSharp/0020__Language-Basics/ACloserLookatException.htm">A Closer Look at Exception</a> 1.17.4. <A href="/Tutorial/CSharp/0020__Language-Basics/UsingExceptionmembers.htm">Using Exception members</a> 1.17.5. <A href="/Tutorial/CSharp/0020__Language-Basics/Exceptionpropagationwithmethods.htm">Exception propagation with methods</a> 1.17.6. <A href="/Tutorial/CSharp/0020__Language-Basics/Anunhandledexception.htm">An unhandled exception</a> 1.17.7. <A href="/Tutorial/CSharp/0020__Language-Basics/CommonlyUsedExceptionsDefinedWithintheSystemNamespace.htm">Commonly Used Exceptions Defined Within the System Namespace </a> 1.17.8. <A href="/Tutorial/CSharp/0020__Language-Basics/Handlingapossibleexception.htm">Handling a possible exception.</a>

Using Exception members

using System; 
 
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.");  
  }  
}
Before exception is generated.
Standard message is:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at MainClass.Main()
Stack trace:    at MainClass.Main()
Message: Index was outside the bounds of the array.
TargetSite: Void Main()
Class defining member: MainClass
Member type: Method
Source: main
Help Link:
After catch statement.