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

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

Текущая версия на 11:39, 26 мая 2010

calls GetBaseException and outputs the error message of the initial exception.

 
using System;
public class Starter {
    public static void Main() {
        try {
            MethodA();
        } catch (Exception except) {
            Exception original = except.GetBaseException();
            Console.WriteLine(original.Message);
        }
    }
    public static void MethodA() {
        try {
            MethodB();
        } catch (Exception except) {
            throw new ApplicationException("Inner Exception", except);
        }
    }
    public static void MethodB() {
        throw new ApplicationException("Innermost Exception");
    }
}


Demonstrates defining and using a custom exception class

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// CustExcp.cs -- Demonstrates defining and using a custom exception class
//
//                Compile this program with the following command line:
//                    C:>csc CustExcp.cs
//
namespace nsCustomException
{
    using System;
    using System.IO;
    
    public class CustExcpclsMain
    {
        static public void Main (string [] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine ("usage: CustExcp FileName String");
                return;
            }
            try
            {
                ReadFile (args[0], args[1]);
                Console.WriteLine (args[1] + " was not found in " + args[0]);
            }
// Custom exception thrown. Display the information.
            catch (clsException e)
            {
                Console.WriteLine ("string {0} first occurs in {1} at Line {2}, Column {3}",
                                   args[1], args[0], e.Line, e.Column);
                Console.WriteLine (e.Found);
                return;
            }
// Check for other possible exceptions.
            catch (ArgumentException)
            {
                Console.WriteLine ("The file name " + args [0] +
                          " is empty or contains an invalid character");
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine ("The file name " + args [0] +
                                   " cannot be found");
            }
            catch (DirectoryNotFoundException)
            {
                Console.WriteLine ("The path for " + args [0] +
                                   " is invalid");
            }
            catch (Exception e)
            {
                Console.WriteLine (e);
            }
        }
        static public void ReadFile (string FileName, string Find)
        {
            FileStream strm;
            StreamReader reader;
            try
            {
                strm = new FileStream (FileName, FileMode.Open);
                reader = new StreamReader (strm);
                int Line = 0;
                while (reader.Peek () >= 0)
                {
                    ++Line;
                    string str = reader.ReadLine ();
                    int index = str.IndexOf (Find);
                    if (index >= 0)
                    {
                        reader.Close ();
                        strm.Close ();
                        clsException ex = new clsException ();
                        ex.Line = Line;
                        ex.Column = index + 1;
                        ex.Found = str;
                        throw (ex);
                    }
                }
                reader.Close ();
                strm.Close ();
                return;
            }
            catch (IOException e)
            {
// If file not found, go back and get another name
                if (e is FileNotFoundException)
                    throw (e);
// Code here to handle other IOException classes
                Console.WriteLine (e.Message);
                throw (new IOException());
            }
       }
    }
// Define a class derived from Exception
    class clsException : Exception
    {
        public int Line = 0;
        public int Column = 0;
        public string Found = null;
    }
}


Derived exceptions must appear before base class exceptions

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Derived exceptions must appear before base class exceptions. 
 
using System; 
 
// Create an exception. 
class ExceptA : ApplicationException { 
  public ExceptA() : base() { } 
  public ExceptA(string str) : base(str) { } 
 
  public override string ToString() { 
    return Message; 
  } 
} 
 
// Create an exception derived from ExceptA 
class ExceptB : ExceptA { 
  public ExceptB() : base() { } 
  public ExceptB(string str) : base(str) { } 
 
  public override string ToString() { 
    return Message;  
  } 
} 
 
public class OrderMatters { 
  public static void Main() { 
    for(int x = 0; x < 3; x++) { 
      try { 
        if(x==0) throw new ExceptA("Caught an ExceptA exception"); 
        else if(x==1) throw new ExceptB("Caught an ExceptB exception"); 
        else throw new Exception(); 
      } 
      catch (ExceptB exc) { 
        // catch the exception 
        Console.WriteLine(exc); 
      } 
      catch (ExceptA exc) { 
        // catch the exception 
        Console.WriteLine(exc); 
      } 
      catch (Exception exc) { 
        Console.WriteLine(exc); 
      } 
    } 
  } 
}


Exception handle with your own exception class

/*
Learning C# 
by Jesse Liberty
Publisher: O"Reilly 
ISBN: 0596003765
*/
 using System;
 namespace ExceptionHandling
 {
     // custom exception class
     class MyCustomException :
         System.ApplicationException
     {
         public MyCustomException(string message):
             base(message) // pass the message up to the base class
         {
         }
     }
    public class TesterExceptionHandling
    {
       public void Run()
       {
           try
           {
               Console.WriteLine("Open file here");
               double a = 0;
               double b = 5;
               Console.WriteLine ("{0} / {1} = {2}",
                   a, b, DoDivide(a,b));
               Console.WriteLine (
                   "This line may or may not print");
           }
               // most derived exception type first
           catch (System.DivideByZeroException e)
           {
               Console.WriteLine(
                   "\nDivideByZeroException! Msg: {0}",
                   e.Message);
               Console.WriteLine(
                   "\nHelpLink: {0}\n", e.HelpLink);
           }
           // catch custom exception
           catch (MyCustomException e)
           {
               Console.WriteLine(
                   "\nMyCustomException! Msg: {0}",
                   e.Message);
               Console.WriteLine(
                   "\nHelpLink: {0}\n", e.HelpLink);
           }
           catch     // catch any uncaught exceptions
           {
               Console.WriteLine(
                   "Unknown exception caught");
           }
           finally
           {
               Console.WriteLine ("Close file here.");
           }
       }
        // do the division if legal
        public double DoDivide(double a, double b)
        {
            if (b == 0)
            {
                DivideByZeroException e =
                    new DivideByZeroException();
                e.HelpLink=
                    "http://www.libertyassociates.ru";
                throw e;
            }
            if (a == 0)
            {
                // create a custom exception instance
                MyCustomException e =
                    new MyCustomException(
                    "Can"t have zero divisor");
                e.HelpLink =
                    "http://www.libertyassociates.ru/NoZeroDivisor.htm";
                throw e;
            }
            return a/b;
        }
        static void Main()
        {
            Console.WriteLine("Enter Main...");
            TesterExceptionHandling t = new TesterExceptionHandling();
            t.Run();
            Console.WriteLine("Exit Main...");
        }
    }
 }


Exception Handling: The Exception Hierarchy 1

using System;

public class ExceptionHierarchy
{
    static int Zero = 0;
    public static void Main()
    {
        try
        {
            int j = 22 / Zero;
        }
        // catch a specific exception
        catch (DivideByZeroException e)
        {
            Console.WriteLine("DivideByZero {0}", e);
        }
        // catch any remaining exceptions
        catch (Exception e)
        {
            Console.WriteLine("Exception {0}", e);
        }
    }
}


Exception Handling: The Exception Hierarchy 2

using System;
public class ExceptionHierarchyNeverExecuted
{
    static int Zero = 0;
    static void AFunction()
    {
        int j = 22 / Zero;
        Console.WriteLine("In AFunction()");
    }
    public static void Main()
    {
        try
        {
            AFunction();
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine("DivideByZero {0}", e);
        }
    }
}


Exception Handling: The Exception Hierarchy 3

using System;
public class ExceptionHierarchyOutOfRangeException
{
    static int Zero = 0;
    static void AFunction()
    {
        try
        {
            int j = 22 / Zero;
        }
       // this exception doesn"t match
        catch (ArgumentOutOfRangeException e)
        {
            Console.WriteLine("OutOfRangeException: {0}", e);
        }
        Console.WriteLine("In AFunction()");
    }
    public static void Main()
    {
        try
        {
            AFunction();
        }
        // this exception doesn"t match
        catch (ArgumentException e)
        {
            Console.WriteLine("ArgumentException {0}", e);
        }
    }
}


Exception Handling User-Defined Exception Classes

/*
A Programmer"s Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/
// 04 - Exception Handling\User-Defined Exception Classes
// copyright 2000 Eric Gunnerson
using System;
public class UserDefinedExceptionClasses
{
    public static void Main()
    {
        Summer summer = new Summer();
        try
        {
            summer.DoAverage();
        }
        catch (CountIsZeroException e)
        {
            Console.WriteLine("CountIsZeroException: {0}", e);
        }
    }
}
public class CountIsZeroException: ApplicationException
{
    public CountIsZeroException()
    {
    }
    public CountIsZeroException(string message)
    : base(message)
    {
    }
    public CountIsZeroException(string message, Exception inner)
    : base(message, inner)
    {
    }
}
public class Summer
{
    int    sum = 0;
    int    count = 0;
    float    average;
    public void DoAverage()
    {
        if (count == 0)
        throw(new CountIsZeroException("Zero count in DoAverage"));
        else
        average = sum / count;
    }
}


illustrates a custom exception

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example13_9.cs illustrates a custom exception
*/
using System;

// declare the CustomException class
class CustomException : ApplicationException
{
  public CustomException(string Message) : base(Message)
  {
    // set the HelpLink and Source properties
    this.HelpLink = "See the Readme.txt file";
    this.Source = "My Example13_9 Program";
  }
}

public class Example13_9
{
  public static void Main()
  {
    try
    {
      // throw a new CustomException object
      Console.WriteLine("Throwing a new CustomException object");
      throw new CustomException("My CustomException message");
    }
    catch (CustomException e)
    {
      // display the CustomException object"s properties
      Console.WriteLine("HelpLink = " + e.HelpLink);
      Console.WriteLine("Message = " + e.Message);
      Console.WriteLine("Source = " + e.Source);
      Console.WriteLine("StackTrace = " + e.StackTrace);
      Console.WriteLine("TargetSite = " + e.TargetSite);
    }
  }
}


illustrates the use of a System.Exception object

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example13_2.cs illustrates the use of a
  System.Exception object
*/
using System;
public class Example13_2
{
  public static void Main()
  {
    try
    {
      int zero = 0;
      Console.WriteLine("In try block: attempting division by zero");
      int myInt = 1 / zero;  // throws the exception
    }
    catch (System.Exception myException)
    {
      // display the exception object"s properties
      Console.WriteLine("HelpLink = " + myException.HelpLink);
      Console.WriteLine("Message = " + myException.Message);
      Console.WriteLine("Source = " + myException.Source);
      Console.WriteLine("StackTrace = " + myException.StackTrace);
      Console.WriteLine("TargetSite = " + myException.TargetSite);
    }
  }
}


refines the System.Exception base class with name of the type and time of exception to create your own Exception

 
using System;
public class ConstructorException : Exception {
    public ConstructorException(object origin)
        : this(origin, null) {
    }
    public ConstructorException(object origin, Exception innerException)
        : base("Exception in constructor", innerException) {
        prop_Typename = origin.GetType().Name;
        prop_Time = DateTime.Now.ToLongDateString() + " " +
            DateTime.Now.ToShortTimeString();
    }
    protected string prop_Typename = null;
    public string Typename {
        get {
            return prop_Typename;
        }
    }
    protected string prop_Time = null;
    public string Time {
        get {
            return prop_Time;
        }
    }
}
public class Starter {
    public static void Main() {
        try {
            MyClass obj = new MyClass();
        } catch (ConstructorException except) {
            Console.WriteLine(except.Message);
            Console.WriteLine("Typename: " + except.Typename);
            Console.WriteLine("Occured: " + except.Time);
        }
    }
}
class MyClass {
    public MyClass() {
        // initialization fails
        throw new ConstructorException(this);
    }
}


Use a custom Exception for RangeArray errors

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use a custom Exception for RangeArray errors. 
  
using System;  
  
// Create an RangeArray exception. 
class RangeArrayException : ApplicationException { 
  // Implement the standard constructors 
  public RangeArrayException() : base() { } 
  public RangeArrayException(string str) : base(str) { }  
 
  // Override ToString for RangeArrayException. 
  public override string ToString() { 
    return Message; 
  } 
} 
 
// An improved version of RangeArray. 
class RangeArray {   
  // private data 
  int[] a; // reference to underlying array   
  int lowerBound; // lowest index 
  int upperBound; // greatest index 
 
  int len; // underlying var for Length property 
    
  // Construct array given its size.  
  public RangeArray(int low, int high) {  
    high++; 
    if(high <= low) { 
      throw new RangeArrayException("Low index not less than high."); 
    } 
    a = new int[high - low];  
    len = high - low;   
 
    lowerBound = low; 
    upperBound = --high; 
  }  
  
  // Read-only Length property.  
  public int Length {  
    get {  
      return len;  
    }  
  }  
 
  // This is the indexer for RangeArray.  
  public int this[int index] {  
    // This is the get accessor.  
    get {  
      if(ok(index)) {  
        return a[index - lowerBound];  
      } else {  
        throw new RangeArrayException("Range Error."); 
      } 
    }  
  
    // This is the set accessor. 
    set {  
      if(ok(index)) {  
        a[index - lowerBound] = value;  
      }  
      else throw new RangeArrayException("Range Error."); 
    }  
  }  
  
  // Return true if index is within bounds.  
  private bool ok(int index) {  
    if(index >= lowerBound & index <= upperBound) return true;  
    return false;  
  }  
}   
   
// Demonstrate the index-range array.  
public class RangeArrayDemo1 {   
  public static void Main() {   
    try { 
      RangeArray ra = new RangeArray(-5, 5);  
      RangeArray ra2 = new RangeArray(1, 10);  
 
      // Demonstrate ra 
      Console.WriteLine("Length of ra: " + ra.Length); 
 
      for(int i = -5; i <= 5; i++) 
        ra[i] = i; 
   
      Console.Write("Contents of ra: "); 
      for(int i = -5; i <= 5; i++) 
        Console.Write(ra[i] + " "); 
 
      Console.WriteLine("\n"); 
 
      // Demonstrate ra2 
      Console.WriteLine("Length of ra2: " + ra2.Length); 
 
      for(int i = 1; i <= 10; i++) 
        ra2[i] = i; 
 
      Console.Write("Contents of ra2: "); 
      for(int i = 1; i <= 10; i++) 
        Console.Write(ra2[i] + " "); 
 
      Console.WriteLine("\n"); 
 
    } catch (RangeArrayException exc) { 
       Console.WriteLine(exc); 
    } 
 
    // Now, demonstrate some errors. 
    Console.WriteLine("Now generate some range errors."); 
 
    // Use an invalid constructor. 
    try { 
      RangeArray ra3 = new RangeArray(100, -10); // Error 
   
    } catch (RangeArrayException exc) { 
       Console.WriteLine(exc); 
    } 
 
    // Use an invalid index. 
    try { 
      RangeArray ra3 = new RangeArray(-2, 2);  
 
      for(int i = -2; i <= 2; i++) 
        ra3[i] = i; 
 
      Console.Write("Contents of ra3: "); 
      for(int i = -2; i <= 10; i++) // generate range error 
        Console.Write(ra3[i] + " "); 
 
    } catch (RangeArrayException exc) { 
       Console.WriteLine(exc); 
    } 
  }  
}


uses some of the properties of the Exception class

 
using System;
using System.Reflection;
public class Starter {
    public static bool bException = true;
    public static void Main() {
        try {
            MethodA();
        } catch (Exception except) {
            Console.WriteLine(except.Message);
            bException = false;
            except.TargetSite.Invoke(null, null);
        }
    }
    public static void MethodA() {
        if (bException) {
            throw new ApplicationException("exception message");
        }
    }
}


Use the NullReferenceException

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use the NullReferenceException. 
 
using System;  
  
class X { 
  int x; 
  public X(int a) { 
    x = a; 
  } 
 
  public int add(X o) { 
    return x + o.x; 
  } 
} 
   
// Demonstrate NullReferenceException. 
public class NREDemo {   
  public static void Main() {   
    X p = new X(10); 
    X q = null; // q is explicitly assigned null 
    int val; 
 
    try { 
      val = p.add(q); // this will lead to an exception 
    } catch (NullReferenceException) { 
      Console.WriteLine("NullReferenceException!"); 
      Console.WriteLine("fixing...\n"); 
 
      // now, fix it 
      q = new X(9);   
      val = p.add(q); 
    } 
 
    Console.WriteLine("val is {0}", val); 
  
  }  
}


Using checked and unchecked

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Using checked and unchecked. 
 
using System; 
 
public class CheckedDemo {  
  public static void Main() {  
    byte a, b; 
    byte result; 
 
    a = 127; 
    b = 127; 
  
    try {  
      result = unchecked((byte)(a * b)); 
      Console.WriteLine("Unchecked result: " + result); 
 
      result = checked((byte)(a * b)); // this causes exception 
      Console.WriteLine("Checked result: " + result); // won"t execute 
    }  
    catch (OverflowException exc) {  
      // catch the exception  
      Console.WriteLine(exc); 
    }  
  }  
}


Using checked and unchecked with statement blocks

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Using checked and unchecked with statement blocks. 
 
using System; 
 
public class CheckedBlocks {  
  public static void Main() {  
    byte a, b; 
    byte result; 
 
    a = 127; 
    b = 127; 
  
    try {  
      unchecked { 
        a = 127; 
        b = 127; 
        result = unchecked((byte)(a * b)); 
        Console.WriteLine("Unchecked result: " + result); 
 
        a = 125; 
        b = 5; 
        result = unchecked((byte)(a * b)); 
        Console.WriteLine("Unchecked result: " + result); 
      } 
 
      checked { 
        a = 2; 
        b = 7; 
        result = checked((byte)(a * b)); // this is OK 
        Console.WriteLine("Checked result: " + result); 
 
        a = 127; 
        b = 127; 
        result = checked((byte)(a * b)); // this causes exception 
        Console.WriteLine("Checked result: " + result); // won"t execute 
      } 
    }  
    catch (OverflowException exc) {  
      // catch the exception  
      Console.WriteLine(exc); 
    }  
  }  
}


Using Exception members

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Using Exception members. 
 
using System; 
 
class ExcTest { 
  public static void genException() { 
    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; 
        Console.WriteLine("nums[{0}]: {1}", i, nums[i]); 
      } 
 
    Console.WriteLine("this won"t be displayed");  
  } 
}     
 
public class UseExcept {  
  public static void Main() {  
  
    try {  
      ExcTest.genException(); 
    }  
    catch (IndexOutOfRangeException exc) {  
      // catch the exception  
      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("After catch statement.");  
  }  
}