Understand Python Return Value in Python Try, Except and Finally for Beginners – Python Tutorial

By | October 14, 2019

If you have used python return statement in python try, except and finally, it is may be confused to understand. In this tutorial, we will explain the return value in python try, except and finally.

Python Try, Except and Finally Statement

To understand python return statement, you can refer to this tutorial.

Understand Python Return Statement for Python Beginners – Python Tutorial

However, look at this example.

def getExceptionReturn():
    try:
        print('run try statement')
        x = 1 / 0
        return 1
    except Exception as e:
        print("run except statement")
        print(e)
        return 0
    finally:
        print('run finally statement')
        return 2
    
x = getExceptionReturn()
print(x)

What the return value of getExceptionReturn() function?

1. 1/0 will raise an exception.

2. except statement will be run, it will return 0.

3. finally statement will be run, it will return 2.

So the return value of getExceptionReturn() function is 0 or 2?

The run result is:

run try statement
run except statement
division by zero
run finally statement
2

The return value is 2, which means the return value in except statement is replaced by return value in finally statement.

Look at this example.

def getExceptionReturn():
    try:
        print('run try statement')
        x = 1 / 1
        return 1
    except Exception as e:
        print("run except statement")
        print(e)
        return 0
    finally:
        print('run finally statement')
        return 2
    
x = getExceptionReturn()
print(x)

The return value of getExceptionReturn() funtion is 1 or 2?

The execution result is:

run try statement
run finally statement
2

The return value is 2, which means return value in try statement is replaced by return value in finally statement.

However, if we do not use  finally statement, the return value is very easy to understand.

If there is not return value in finally statement?

Here is an example.

def getExceptionReturn():
    try:
        print('run try statement')
        x = 1 / 1
        return 1
    except Exception as e:
        print("run except statement")
        print(e)
        return 0
    finally:
        print('run finally statement')
    
x = getExceptionReturn()
print(x)

In this example, there is not any return value in finally statement, so the return value of getExceptionReturn() should be 1.

The execution result is:

run try statement
run finally statement
1

Leave a Reply

Your email address will not be published. Required fields are marked *