Demonstates the possible uses of a finally block : Exception Finally : Language Basics C# Source Code


Custom Search

C# Source Code » Language Basics » Exception Finally »

 

Demonstates the possible uses of a finally block









    

/*
C# Programming Tips & 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\r\n");
            }
            try
            {
                SmallProblem ();
            }
            catch (clsException e)
            {
                Console.WriteLine (e.Message);
            }
            finally
            {
                Console.WriteLine ("But not big enough to exit\r\n");
            }
            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;
    }
}

           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Language Basics
» Exception Finally