Mailing List Archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] [OT] C# question -- try / catch / finally



On 22/11/2013 01:00, jep200404@example.com wrote:

> A web search for C# try finally led to a page by C#'s sponsor 
> which seemed to indicate that the finally is executed even if 
> a break, continue, goto, or return happens in the try section.

Bingo!

I missed this detail on my travels through t'interweb yesterday. A quick
demonstration of this principle shows the logic behind it:

/****************************************************************/
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 9;
            int b = 3;
            int c = doDivide(a, b);
            Console.WriteLine("{0} / {1} = {2}",a,b,c);
            Console.ReadLine();
        }

        static int doDivide(int numerator, int denominator)
        {
            try
            {
                Console.WriteLine("in doDivide()");
                return (numerator / denominator);
            }
            catch (DivideByZeroException)
            {
                Console.WriteLine("Caught division by zero!");
            }
            finally
            {
                Console.WriteLine("in finally clause");
            }
            return -1;
        }
    }
}
/****************************************************************/

This generates:

in doDivide()
in finally clause
9 / 3 = 3

If b=0 instead of 3 above:

in doDivide()
Caught division by zero!
in finally clause
9 / 0 = -1

Thanks to all for your input. This makes a lot more sense now.

-- 
Godwin Stewart -- <gstewart@example.com>


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links