Python 예외 처리 finally와 else 차이

예외 처리로 에러를 처리하는 경우 사용할 수 있는 문법으로 finallyelse가 있습니다.

사용 방법과 어떤 동작을 하는지 알아보겠습니다.

먼저 elsetry문 내에서 에러가 발생하지 않은 경우 처리를 하게 됩니다.

 

else 예제

try:
	a = 10 / 1
	print("{0}".format(a))
except ZeroDivisionError as e:
	print("ZeroDivisionError!!")
else:
	print("else statement")
finally:
	print("finally statement")

 

결과

10.0
else statement
finally statement

else에 작성한 출력문이 표시되었습니다.

그리고 finally에 작성한 문자열도 표시되었습니다.

이번에는 에러가 발생하는 경우를 보겠습니다.

 

에러 예제

try:
	a = 10 / 0
	print("{0}".format(a))
except ZeroDivisionError as e:
	print("ZeroDivisionError!!")
else:
	print("else statement")
finally:
	print("finally statement")

 

결과

ZeroDivisionError!!
finally statement

예외가 발생했기 때문에 except 작성한 문자열이 출력됐습니다.

그리고 finally에 작성한 문자열도 출력됐습니다.

finally는 정상 종료된 경우와 에러가 발생한 경우 모두 출력되었습니다.

에러 여부와 상관없이 무조건 실행됩니다.

댓글