code

Python try finally 블록 반환

codestyles 2021. 1. 10. 17:16
반응형

Python try finally 블록 반환


이 질문에 이미 답변이 있습니다.

아래에 흥미로운 코드가 있습니다.

def func1():
    try:
        return 1
    finally:
        return 2

def func2():
    try:
        raise ValueError()
    except:
        return 1
    finally:
        return 3

func1()
func2()

누군가가이 두 함수를 반환하는 결과를 설명하고 그 이유를 설명해주십시오. 즉, 실행 순서를 설명하십시오.


Python 문서에서

finally 절은 예외가 발생했는지 여부에 관계없이 try 문을 떠나기 전에 항상 실행됩니다. try 절에서 예외가 발생하고 except 절에 의해 처리되지 않은 경우 (또는 except 또는 else 절에서 발생한 경우), finally 절이 실행 된 후 다시 발생합니다. finally 절 은 break, continue 또는 return 문을 통해 try 문의 다른 절이 남아있을 때 "출구 중"에서도 실행됩니다 . 더 복잡한 예제 (같은 try 문에 except 및 finally 절이있는 경우 Python 2.5에서 작동 함) :

따라서 try / except 블록이 return을 사용하여 남겨 지면 반환 값을 주어진 값으로 설정합니다. finally 블록은 항상 실행되며 다른 반환을 사용하는 동안 리소스 등을 해제하는 데 사용해야합니다. 원본을 덮어 씁니다.

귀하의 특별한 경우 에는 finally 블록에서 반환되는 값 이므로 func1()return 2func2()return 3입니다.


항상 finally블록으로 이동 하므로 return에서 를 무시합니다 . 당신이있을 것입니다 경우 하고 , 그 값을 반환합니다.tryexceptreturntryexcept

def func1():
    try:
        return 1 # ignoring the return
    finally:
        return 2 # returns this return

def func2():
    try:
        raise ValueError()
    except:
        # is going to this exception block, but ignores the return because it needs to go to the finally
        return 1
    finally:
        return 3

def func3():
    return 0 # finds a return here, before the try except and finally block, so it will use this return 
    try:
        raise ValueError()
    except:
        return 1
    finally:
        return 3


func1() # returns 2
func2() # returns 3
func3() # returns 0

퍼팅 print정말 도움이 사전에 정말 문 :

def func1():
    try:
        print 'try statement in func1. after this return 1'
        return 1
    finally:
        print 'after the try statement in func1, return 2'
        return 2

def func2():
    try:
        print 'raise a value error'
        raise ValueError()
    except:
        print 'an error has been raised! return 1!'
        return 1
    finally:
        print 'okay after all that let\'s return 3'
        return 3

print func1()
print func2()

다음을 반환합니다.

try statement in func1. after this return 1
after the try statement in func1, return 2
2
raise a value error
an error has been raised! return 1!
okay after all that let's return 3
3

You'll notice that python always returns the last thing to be returned, regardless that the code "reached" return 1 in both functions.

A finally block is always run, so the last thing to be returned in the function is whatever is returned in the finally block. In func1, that's 2. In func2, that's 3.


func1() returns 2. func2() returns 3.

finally block is executed finally regardless or exception.

You can see order of execution using debugger. For example, see a screencast.

ReferenceURL : https://stackoverflow.com/questions/19805654/python-try-finally-block-returns

반응형