Algorithms, Blockchain and Cloud

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?

#!/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.

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

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) —

235 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# (AMP Version)

Exit mobile version