Finally Block in C#


In [here], the readers would find that it is illegal to put a return statement in the finally block.

Here, we will conduct experiments to check if the finally block will work as expected (executed anyway if there is a return in the try block).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
 
namespace ConsoleApplication1
{
    class Program
    {
        static int test()
        {
            try
            {
                //throw new Exception("Throws Exception"); 
                return 1;
            }
            catch (Exception e)
            {
                return -1;
            }
            finally
            {
                Console.WriteLine("in Finally");
            }
        }
 
        static void Main(string[] args)
        {
            Console.WriteLine(test());
            Console.ReadLine();
        }
    }
}
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static int test()
        {
            try
            {
                //throw new Exception("Throws Exception"); 
                return 1;
            }
            catch (Exception e)
            {
                return -1;
            }
            finally
            {
                Console.WriteLine("in Finally");
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine(test());
            Console.ReadLine();
        }
    }
}

The output is as expected with printing message “in Finally” and “1”.

If we raise and exception in the try block, the finally will still be executed. This is good, if you have a multiple returns in the try block. I guess this phenomena is similar in other programming languages.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
211 words
Last Post: Using Inline Assembly at Timus Online Judge
Next Post: Using Minimum Spanning Tree to Solve the Graph-releated Problem: Learning Languages

The Permanent URL is: Finally Block in C#

Leave a Reply