illustrates the use of a System.Exception object

image_pdfimage_print

   

/*
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);

    }

  }

}

           
          


Demonstrates defining and using a custom exception class

image_pdfimage_print
   

/*
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&#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;
    }
}


           
          


illustrates a custom exception

image_pdfimage_print

   

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

    }

  }

}


           
          


Exception handle with your own exception class

image_pdfimage_print

   

/*
Learning C# 
by Jesse Liberty

Publisher: O&#039;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(
                   "
DivideByZeroException! Msg: {0}",
                   e.Message);
               Console.WriteLine(
                   "
HelpLink: {0}
", e.HelpLink);
           }

           // catch custom exception
           catch (MyCustomException e)
           {
               Console.WriteLine(
                   "
MyCustomException! Msg: {0}",
                   e.Message);
               Console.WriteLine(
                   "
HelpLink: {0}
", 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.com";
                throw e;
            }
            if (a == 0)
            {
                // create a custom exception instance
                MyCustomException e =
                    new MyCustomException(
                    "Can&#039;t have zero divisor");
                e.HelpLink =
                    "http://www.libertyassociates.com/NoZeroDivisor.htm";
                throw e;
            }
            return a/b;
        }

        static void Main()
        {
            Console.WriteLine("Enter Main...");
            TesterExceptionHandling t = new TesterExceptionHandling();
            t.Run();
            Console.WriteLine("Exit Main...");
        }
    }
 }

           
          


Shows how multiple objects may subscribe to the same event

image_pdfimage_print

   


/*
C# Programming Tips &amp; Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
 // Subscrib.cs -- Shows how multiple objects may subscribe to the same
//                event.
//
//                Compile this program with the following command line:
//                    C:>csc Subscrib.cs
using System;

namespace nsEvents
{
    public class Subscrib
    {
        // Declare an instance of the clsDelegate class. The event variable
        // is not static.
        static public clsDelegate dlg = new clsDelegate ();
        static public void Main ()
        {
            // Add clsMain to the event list
            dlg.DoEvent += new clsDelegate.StringHandler (ShowEvent);
            // Create subscribers for the event
            clsSubscriber sub = new clsSubscriber ();
            clsNextSubscriber sub2 = new clsNextSubscriber ();
            // Fire the event.
            dlg.FireEvent ("Fired from Main()");
        }
        static public void ShowEvent (string str)
        {
            Console.WriteLine ("Main handled event: " + str);
        }
    }


    public class clsDelegate
    {
        
        // Declare a delegate for the event
        public delegate void StringHandler (string str);
        
        // A variable to hold the delegate
        public event StringHandler DoEvent;
        
        // This method will trigger the event.
        public void FireEvent (string str)
        {
            if (DoEvent != null)
                DoEvent (str);
        }
    }

    public class clsSubscriber
    {
        public clsSubscriber ()
        {
            Subscrib.dlg.DoEvent +=
                         new clsDelegate.StringHandler (SubscribeEvent);
        }
        public void SubscribeEvent (string str)
        {
            Console.WriteLine ("Subscriber handled event: " + str);
        }
    }
    public class clsNextSubscriber
    {
        public clsNextSubscriber ()
        {
            Subscrib.dlg.DoEvent +=
                         new clsDelegate.StringHandler (SubscribeEvent);
        }
        public void SubscribeEvent (string str)
        {
            Console.WriteLine ("Next Subscriber handled event: " + str);
        }
    }
}




           
          


Demonstrate passing an object to an event handler and performing the proper cast in the method

image_pdfimage_print

   


/*
C# Programming Tips &amp; Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
 
// ObjEvent.cs -- Demonstrate passing an object to an event handler and
//                performing the proper cast in the method.
//
//                Compile this program with the following command line:
//                    C:>csc ObjEvent.cs
using System;

namespace nsEvents
{
    public class ObjEvent1
    {
        public delegate void EventHandler (object obj);
        public event EventHandler EvInvoke;

        public void FireEvent (object obj)
        {
            if (obj != null)
                EvInvoke (obj);
        }

        static public void Main ()
        {
            ObjEvent1 main = new ObjEvent1 ();
            main.EvInvoke = new ObjEvent1.EventHandler (ObjEvent);
            main.FireEvent (42);
            main.FireEvent (42.0);
        }
        static void ObjEvent (object obj)
        {
            if (obj is double)
            {
                Console.WriteLine ("Received a double object: " + (double) obj);
            }
            else if (obj is int)
            {
                Console.WriteLine ("Received an int object: " + (int) obj);
            }
        }
    }
}



           
          


illustrates the use of an event

image_pdfimage_print

   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example12_4.cs illustrates the use of an event
*/

using System;


// declare the MeltdownEventArgs class (implements EventArgs)
class MeltdownEventArgs : EventArgs
{

  // declare a private field named message
  private string message;

  // define a constructor
  public MeltdownEventArgs(string message)
  {
    this.message = message;
  }

  // define a property to get the message
  public string Message
  {
    get
    {
      return message;
    }
  }

}


// declare the Reactor class
class Reactor
{

  // declare a private field named temperature
  private int temperature;

  // declare a delegate class named MeltdownHandler
  public delegate void MeltdownHandler(
    object reactor,
    MeltdownEventArgs myMEA
  );

  // declare an event named OnMeltdown
  public event MeltdownHandler OnMeltdown;

  // define a property to set the temperature
  public int Temperature
  {
    set
    {
      temperature = value;

      // if the temperature is too high, the reactor melts down
      if (temperature > 1000)
      {
        MeltdownEventArgs myMEA =
          new MeltdownEventArgs("Reactor meltdown in progress!");
          OnMeltdown(this, myMEA);
      }
    }
  }

}


// declare the ReactorMonitor class
class ReactorMonitor
{

  // define a constructor
  public ReactorMonitor(Reactor myReactor)
  {
    myReactor.OnMeltdown +=
      new Reactor.MeltdownHandler(DisplayMessage);
  }

  // define the DisplayMessage() method
  public void DisplayMessage(
    object myReactor, MeltdownEventArgs myMEA
  )
  {
    Console.WriteLine(myMEA.Message);
  }

}


public class Example12_4
{

  public static void Main()
  {

    // create a Reactor object
    Reactor myReactor = new Reactor();

    // create a ReactorMonitor object
    ReactorMonitor myReactorMonitor = new ReactorMonitor(myReactor);

    // set myReactor.Temperature to 100 degrees Centigrade
    Console.WriteLine("Setting reactor temperature to 100 degrees Centigrade");
    myReactor.Temperature = 100;

    // set myReactor.Temperature to 500 degrees Centigrade
    Console.WriteLine("Setting reactor temperature to 500 degrees Centigrade");
    myReactor.Temperature = 500;

    // set myReactor.Temperature to 2000 degrees Centigrade
    // (this causes the reactor to meltdown)
    Console.WriteLine("Setting reactor temperature to 2000 degrees Centigrade");
    myReactor.Temperature = 2000;

  }

}