Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird Try-Except-Else-Finally behavior with Return statements

This is some code that is behaving peculiarly. This is a simplified version of the behavior that I've written. This will still demonstrate the weird behavior and I had some specific questions on why this is occurring.

I'm using Python 2.6.6 on Windows 7.

def demo1():     try:         raise RuntimeError,"To Force Issue"     except:         return 1     else:         return 2     finally:         return 3  def demo2():     try:         try:             raise RuntimeError,"To Force Issue"         except:             return 1         else:             return 2         finally:             return 3     except:         print 4     else:         print 5     finally:         print 6 

Results:

>>> print demo1() 3 >>> print demo2() 6 3 
  • Why is demo one returning 3 instead of 1?
  • Why is demo two printing 6 instead of printing 6 w/ 4 or 5?
like image 805
Kyle Owens Avatar asked Jun 22 '12 21:06

Kyle Owens


People also ask

Is finally executed if return in try Python?

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.

Can you put a return statement in a try?

you can use a return statement inside the try block, but you have to place another return outside the try block as well. If you pass true while calling sayHello method, it would return from try block. A return statement has to be at the method level instead of at any other specific level.

Can we use return in except Python?

Yes, you can use try around a return .

Can we return value from except block in python?

When an exception occurs, both finally and except blocks execute before return . Otherwise only finally executes and else doesn't because the function has already returned. Show activity on this post. The else block isn't executed because you have left the function before it got a chance to do so.


1 Answers

Because finally statements are guaranteed to be executed (well, presuming no power outage or anything outside of Python's control). This means that before the function can return, it must run the finally block, which returns a different value.

The Python docs state:

When a return, break or continue statement is executed in the try suite of a try…finally statement, the finally clause is also executed ‘on the way out.’

The return value of a function is determined by the last return statement executed. Since the finally clause always executes, a return statement executed in the finally clause will always be the last one executed:

This means that when you try to return, the finally block is called, returning it's value, rather than the one that you would have had.

like image 175
Gareth Latty Avatar answered Oct 12 '22 15:10

Gareth Latty