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");
    }
}

    


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); } } } } [/csharp]

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(" "); // 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(" "); } 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); } } } [/csharp]

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...
"); 
 
      // now, fix it 
      q = new X(9);   
      val = p.add(q); 
    } 
 
    Console.WriteLine("val is {0}", val); 
  
  }  
}


           
          


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."); } } [/csharp]

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&#039;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);

    }

  }

}

           
          


Demonstrates defining and using a custom exception class

   

/*
C# Programming Tips &amp; 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&#91;0&#93;, args&#91;1&#93;);
                Console.WriteLine (args&#91;1&#93; + " was not found in " + args&#91;0&#93;);
            }
// Custom exception thrown. Display the information.
            catch (clsException e)
            {
                Console.WriteLine ("string {0} first occurs in {1} at Line {2}, Column {3}",
                                   args&#91;1&#93;, args&#91;0&#93;, e.Line, e.Column);
                Console.WriteLine (e.Found);
                return;
            }
// Check for other possible exceptions.
            catch (ArgumentException)
            {
                Console.WriteLine ("The file name " + args &#91;0&#93; +
                          " is empty or contains an invalid character");
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine ("The file name " + args &#91;0&#93; +
                                   " cannot be found");
            }
            catch (DirectoryNotFoundException)
            {
                Console.WriteLine ("The path for " + args &#91;0&#93; +
                                   " 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;
    }
}