Demonstrate exception handling

image_pdfimage_print

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Demonstrate exception handling.

using System;

public class ExcDemo1 {
public static void Main() {
int[] nums = new int[4];

try {
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"); } catch (IndexOutOfRangeException) { // catch the exception Console.WriteLine("Index out-of-bounds!"); } Console.WriteLine("After catch statement."); } } [/csharp]

Several catch branches

image_pdfimage_print

   

/*
Learning C# 
by Jesse Liberty

Publisher: O&#039;Reilly 
ISBN: 0596003765
*/

 using System;

 namespace ExceptionHandling
 {
    public class TesterExceptionHandling4
    {

       public void Run()
       {
           try
           {
               double a = 5;
               double b = 0;
               Console.WriteLine("Dividing {0} by {1}...",a,b);
               Console.WriteLine ("{0} / {1} = {2}",
                   a, b, DoDivide(a,b));
           }

               // most derived exception type first
           catch (System.DivideByZeroException)
           {
               Console.WriteLine(
                   "DivideByZeroException caught!");
           }

           catch (System.ArithmeticException)
           {
               Console.WriteLine(
                   "ArithmeticException caught!");
           }

               // generic exception type last
           catch
           {
               Console.WriteLine(
                   "Unknown exception caught");
           }
       }

        // do the division if legal
        public double DoDivide(double a, double b)
        {
            if (b == 0)
                throw new System.DivideByZeroException();
            if (a == 0)
                throw new System.ArithmeticException();
            return a/b;
        }


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


    }
 }

           
          


Demonstrates using if statements to sort out an IOException

image_pdfimage_print
   

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

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// IOExcept.cs -- Demonstrates using if statements to sort out an IOException
//
//                Compile this program with the following command line:
//                    C:>csc IOExcept.cs
//
namespace nsExcept
{
    using System;
    using System.IO;
    public class IOExcept
    {
        static public void Main (string [] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine ("Please enter a file name");
                return;
            }
            ReadFile (args[0]);
        }
        static public void ReadFile (string FileName)
        {
            FileStream strm = null;
            StreamReader reader = null;
            try
            {
                strm = new FileStream (FileName, FileMode.Open,
                                                   FileAccess.Read);
                reader = new StreamReader (strm);
                while (reader.Peek() > 0)
                {
                    string str = reader.ReadLine();
                    Console.WriteLine (str);
                }
            }
            catch (IOException e)
            {
                if (e is EndOfStreamException)
                {
                    Console.WriteLine ("Attempted to read beyond end of file");
                }
                else if (e is FileNotFoundException)
                {
                    Console.WriteLine ("The file name " + FileName +
                                       " cannot be found");
                    return;
                }
                else if (e is DirectoryNotFoundException)
                {
                    Console.WriteLine ("The path for name " + FileName +
                                       " cannot be found");
                    return;
                }
                else if (e is FileLoadException)
                {
                    Console.WriteLine ("Cannot read from " + FileName);
                }
                reader.Close();
                strm.Close ();
            }
            catch (Exception e)
            {
                Console.WriteLine (e.Message);
            }
        }
    }
}



           
          


Throw a format exception purposely to demonstrate catching a FormatException

image_pdfimage_print
   

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

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

//
// FormExce.cs -- This program will throw a format exception purposeely
//                to demonstrate catching a FormatException.
//
//                Compile this program with the following command line:
//                    C:>csc FormExcep.cs
//
namespace nsExceptions
{
    using System;
    public class FormExce
    {
        static public void Main ()
        {
            const double pi = 3.14159;
            try
            {
                Console.WriteLine ("pi = {0,0:f5", pi);
            }
            catch (FormatException e)
            {
                Console.WriteLine (e.Message);
            }
        }
    }
}


           
          


Catches an exception that was thrown in a component

image_pdfimage_print
   

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

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// FileOpen.cs -- Catches an exception that was thrown in a component
//
//                Compile this program with the following command line:
//                    C:>csc /r:fopen.dll FileOpen.cs
//
namespace nsFileOpen
{
    using System;
    using System.IO;
    class clsMain
    {
        static public void Main ()
        {
            clsFile file;
            try
            {
                file = new clsFile ("");
            }
            catch (Exception e)
            {
                Console.WriteLine (e.Message);
                Console.WriteLine ("Exception handled in client");
            }
        }
    }
}


// Fopen.cs -- program to show exception handling in a component
//
//             Compile this program with the following command line:
//                 C:>csc /t:library Fopen.cs
//
namespace nsFileOpen
{
    using System;
    using System.IO;
    public class clsFile
    {
        FileStream strm;
        public clsFile (string FileName)
        {
            strm = new FileStream (FileName, FileMode.Open,
                                             FileAccess.Read);
        }
    }
}



           
          


Demonstrates stacking catch blocks to provide alternate code for more than one exception type

image_pdfimage_print
   

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

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// Except.cs -- Demonstrates stacking catch blocks to provide alternate code for
// more than one exception type.
//
// Compile this program with the following command line:
//    C:>csc Except.cs
//
namespace nsExcept
{
    using System;
    using System.IO;
    
    public class Except
    {
        static public void Main (string [] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine ("Please enter a file name");
                return;
            }
            try
            {
                ReadFile (args[0]);
            }
            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)
        {
            FileStream strm = new FileStream (FileName, FileMode.Open,
                                                        FileAccess.Read);
            StreamReader reader = new StreamReader (strm);
            string str = reader.ReadToEnd ();
            Console.WriteLine (str);
        }
    }
}


           
          


Catch Divide By Zero Exception

image_pdfimage_print

   

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

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

namespace nsDivZero
{
    using System;
    public class DivZero
    {
        static public void Main ()
        {
            // Set an integer equal to 0
            int IntVal1 = 0;
            // and another not equal to zero
            int IntVal2 = 57;
            try
            {
                Console.WriteLine ("{0} / {1} = {2}", IntVal2, IntVal1, IntResult (IntVal2, IntVal1) / IntResult (IntVal2, IntVal1));
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine (e.Message);
            }
            // Set a double equal to 0
            double dVal1 = 0.0;
            double dVal2 = 57.3;
            try
            {
                Console.WriteLine ("{0} / {1} = {2}", dVal2, dVal1, DoubleResult (dVal2, dVal1));
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine (e.Message);
            }
        }
        static public int IntResult (int num, int denom)
        {
            return (num / denom);
        }
        static public double DoubleResult (double num, double denom)
        {
            return (num / denom);
        }
    }
}