Return in Try-Finally for Python/Java/Delphi/C#


Return in Try-Finally for Python

What do you think the following will return in Python?

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python
# https://helloacm.com
 
def test():
    try:
        return True
    finally:
        return False
 
print test()
#!/usr/bin/env python
# https://helloacm.com

def test():
    try:
        return True
    finally:
        return False

print test()

Well, this is not a good practice because it is misleading and confusing. The above code will print False because the statements in finally will be invoked anyway.

Return in Try-Finally for Java

In Java, it is the same.

1
2
3
4
5
6
7
8
try 
{
    return (true);
} 
finally 
{
    return (false);
}
try 
{
    return (true);
} 
finally 
{
    return (false);
}

Return in Try-Finally for Delphi

How about other programming languages? Delphi is the same.

program Test;
{$APPTYPE CONSOLE}

function test1: boolean;
begin
  try
    Result := true;
    Exit;
  finally
    Result := false;
  end;
end;

begin
  writeln(test1);
  readln;
end.

Return in Try-Finally for C#

However, in C#, the following code won’t compile and the erros will be shown:

Control cannot leave the body of a finally clause

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
using System;
using System.Collections;
 
namespace ConsoleApplication1
{
    class Program
    {
        static bool test()
        {
            try
            {
                return (true);
            }
            finally
            {
                return (false);
            }
        }
 
        static void Main(string[] args)
        {
            Console.WriteLine(test());
        }
    }
}
using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static bool test()
        {
            try
            {
                return (true);
            }
            finally
            {
                return (false);
            }
        }

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

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
252 words
Last Post: Get Folder Size in PHP
Next Post: Brainfuck Interpreter in Python

The Permanent URL is: Return in Try-Finally for Python/Java/Delphi/C#

One Response

  1. Xiaoming Tu

Leave a Reply