Demonstates the possible uses of a finally block : Exception Finally « Language Basics « C# / C Sharp






Demonstates the possible uses of a finally block

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

           
       








Related examples in the same category

1.Use final to deal with custom Exceptions
2.illustrates a try, catch, and finally blockillustrates a try, catch, and finally block
3.Exception with finallyException with finally
4.Exception handle with finallyException handle with finally
5.Use finallyUse finally
6.Exception Handling Finally