return eats exception

后端 未结 4 2097
臣服心动
臣服心动 2020-11-28 10:44

I found the following behavior at least weird:

def errors():
    try:
        ErrorErrorError
    finally:
        return 10

print errors()
# print         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 10:54

    Here is an interesting comparison for return in finally block, among - Java/C#/Python/JavaScript: (archive link)

    Return From Finally

    Just today I was helping with some bug in Java and came across interesting problem - what happens if you use return within try/catch statement? Should the finally section fire up or not? I simplified the problem to following code snippet:

    What does the following code print out?

    class ReturnFromFinally {  
     public static int a() {  
      try {  
       return 1;  
      }  
      catch (Exception e) {}  
      finally{  
       return 2;  
      }  
     }  
    
            public static void main(String[] args) {  
      System.out.println(a());  
            }  
    }  
    

    My initial guess would be, that it should print out 1, I'm calling return, so I assume, one will be returned. However, it is not the case:

    I understand the logic, finally section has to be executed, but somehow I feel uneasy about this. Let's see what C# does in this case:

    class ReturnFromFinally  
    {  
     public static int a()  
     {  
      try {  
              return 1;  
      }  
      catch (System.Exception e) {}  
      finally   
      {   
       return 2;  
      }  
     }  
    
     public static void Main(string[] args)  
     {  
      System.Console.WriteLine(a());  
     }  
    }  
    

    I prefer much rather this behavior, control flow cannot be messed with in finally clause, so it prevents us from shooting ourself in the foot. Just for the sake of completeness, let's check what other languages do.

    Python:

    def a():  
     try:  
      return 1  
     finally:  
      return 2  
    print a()  
    

    JavaScript:

      
    Click here  
    

    There is no finally clause in C++ and PHP, so I can't try out the last two languages I have compiler/interpreter for.

    Our little experiment nicely showed, that C# has the nicest approach to this problem, but I was quite surprised to learn, that all the other languages handle the problem the same way.

提交回复
热议问题