Use finally

/*
C#: The Complete Reference
by Herbert Schildt

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

// Use finally.

using System;

class UseFinally {
public static void genException(int what) {
int t;
int[] nums = new int[2];

Console.WriteLine(“Receiving ” + what);
try {
switch(what) {
case 0:
t = 10 / what; // generate div-by-zero error
break;
case 1:
nums[4] = 4; // generate array index error.
break;
case 2:
return; // return from try block
}
}
catch (DivideByZeroException) {
// catch the exception
Console.WriteLine(“Can't divide by Zero!”);
return; // return from catch
}
catch (IndexOutOfRangeException) {
// catch the exception
Console.WriteLine(“No matching element found.”);
}
finally {
Console.WriteLine(“Leaving try.”);
}
}
}

public class FinallyDemo {
public static void Main() {

for(int i=0; i < 3; i++) { UseFinally.genException(i); Console.WriteLine(); } } } [/csharp]

Exception handle with finally


   

/*
Learning C# 
by Jesse Liberty

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

 using System;

 namespace ExceptionHandling
 {
    public class TesterExceptionHandling6
    {
       public void Run()
       {
           try
           {
               Console.WriteLine("Open file here");
               double a = 12;
               double b = 0;
               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);
               Console.WriteLine(
                   "
Here&#039;s a stack trace: {0}
",
                   e.StackTrace);
           }
           catch
           {
               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)
                throw new ArithmeticException();
            return a/b;
        }

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


Exception with finally


   

/*
Learning C# 
by Jesse Liberty

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

 using System;

 namespace ExceptionHandling
 {
    public class TesterExceptionHandling5
    {
       public void Run()
       {
           try
           {
               Console.WriteLine("Open file here");
               double a = 5;
               double b = 0;
               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)
           {
               Console.WriteLine(
                   "DivideByZeroException caught!");
           }
           catch
           {
               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)
                throw new System.DivideByZeroException();
            if (a == 0)
                throw new System.ArithmeticException();
            return a/b;
        }

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

           
          


Demonstates the possible uses of a finally block


   

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

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

// Finally.cs -- Demonstates the possible uses of a finally block
//
//               Compile this program with the following command line:
//                   C:>csc Finally.cs
//
namespace nsFinally
{
    using System;
    public class Finally
    {
        static public void Main ()
        {
            try
            {
                NoProblem ();
            }
// No exception possible here. Use finally without a catch
            finally
            {
                Console.WriteLine ("No problem at all
");
            }
            try
            {
                SmallProblem ();
            }
            catch (clsException e)
            {
                Console.WriteLine (e.Message);
            }
            finally
            {
                Console.WriteLine ("But not big enough to exit
");
            }
            try
            {
                BigProblem ();
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine (e.Message);
            }
            finally
            {
                Console.WriteLine ("But the finally block still executes.");
            }
        }
        static public void NoProblem()
        {
        }
        static public void SmallProblem ()
        {
            clsException ex = new clsException();
            ex.Message = "Small problem encountered";
            throw (ex);
        }
        static public void BigProblem ()
        {
            clsException ex = new clsException();
            ex.Message = "Big trouble. Applicaion must end.";
            throw (ex);
        }
    }
// Define a custom exception class just for a personalized message
    public class clsException : Exception
    {
        new public string Message = null;
    }
}

           
          


illustrates a try, catch, and finally block


   

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

Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example13_1.cs illustrates a try, catch, and finally block
*/

using System;

public class Example13_1
{

  public static void Main()
  {

    try
    {

      // code that throws an exception
      int zero = 0;
      Console.WriteLine("In try block: attempting division by zero");
      int myInt = 1 / zero;  // throws the exception
      Console.WriteLine("You never see this message!");

    }
    catch
    {

      // code that handles the exception
      Console.WriteLine("In catch block: an exception was thrown");

    }
    finally
    {

      // code that does any cleaning up
      Console.WriteLine("In finally block: do any cleaning up here");

    }

  }

}


           
          


Use final to deal with custom Exceptions

   
 
using System;
using System.Runtime.Serialization;

class TestDirectoryMissingException : ApplicationException {
    public TestDirectoryMissingException() :
        base() {
    }
    public TestDirectoryMissingException(string msg) :
        base(msg) {
    }
    public TestDirectoryMissingException(SerializationInfo info, StreamingContext cxt) :
        base(info, cxt) {
    }
    public TestDirectoryMissingException(string msg, Exception inner) :
        base(msg, inner) {
    }

}
class MainClass {
    static void DoStuff() {
        if (System.IO.Directory.Exists("c:	est") == false)
            throw new TestDirectoryMissingException("The test directory does not exist");
    }
    static void Main(string[] args) {
        try { 
            DoStuff();
        } catch (System.IO.DirectoryNotFoundException e1) {
            System.Console.WriteLine(e1.StackTrace);
            System.Console.WriteLine(e1.Source);
            System.Console.WriteLine(e1.TargetSite);
        } catch (System.IO.FileNotFoundException e2) {
        } catch (System.Exception e) {
            System.Console.WriteLine("Ex");
        } finally {
            System.Console.WriteLine("final");
        }
    }
}

    


Exception Handling User-Defined Exception Classes


   

/*
A Programmer&#039;s Introduction to C# (Second Edition)
by Eric Gunnerson

Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/

// 04 - Exception HandlingUser-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;
    }
}