Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 정리 작업 정의


우리 프로그램이 완벽하게 실행되는지 또는 약간의 오류가 발생하는지에 관계없이 우리 프로그램이 이 특정 작업을 수행하기를 원할 때 수많은 상황이 발생합니다. 주로 오류나 예외를 포착하기 위해 try 및 except 블록을 사용합니다.

"try" 문은 어떤 상황에서도 실행되어야 하는 '정리 작업'을 정의하기 위한 매우 유용한 선택적 절을 제공합니다. 예를 들어 -

>>> try:
   raise SyntaxError
finally:
   print("Learning Python!")
Learning Python!
Traceback (most recent call last):
   File "<pyshell#11>", line 2, in <module>
      raise SyntaxError
   File "<string>", line None
SyntaxError: <no detail available>

마지막 절은 무엇이든 상관없이 실행되지만 else 절은 예외가 발생하지 않은 경우에만 실행됩니다.

예시 1 − 모든 것이 괜찮아 보이고 예외 없이 파일에 쓰는 경우(프로그램이 작동 중임) 다음을 출력하는 아래 예를 고려하십시오. −

file = open('finally.txt', 'w')
try:
   file.write("Testing1 2 3.")
   print("Writing to file.")
except IOError:
   print("Could not write to file.")
else:
   print("Write successful.")
finally:
   file.close()
   print("File closed.")

위의 프로그램을 실행하면 -

가 됩니다.
Writing to file.
Write successful.
File closed.

예시 2 − 파일을 읽기 전용으로 만들어 예외를 발생시키고 이에 쓰기를 시도하여 예외를 발생시키도록 합시다.

file = open('finally.txt', 'r')
try:
   file.write("Testing1 2 3.")
   print("Writing to file.")
except IOError:
   print("Could not write to file.")
else:
   print("Write successful.")
finally:
   file.close()
   print("File closed.")

위의 프로그램은 −

와 같은 출력을 제공합니다.
Could not write to file.
File closed.

오류가 있지만 처리할 예외 절을 두지 않은 경우를 대비합니다. 이러한 경우 정리 작업(최종 차단)이 먼저 실행된 다음 컴파일러에서 오류가 발생합니다. 아래의 예를 통해 개념을 이해합시다 -

예시

file = open('finally.txt', 'r')
try:
   file.write(4)
   print("Writing to file.")
except IOError:
   print("Could not write to file.")
else:
   print("Write successful.")
finally:
   file.close()
   print("File closed.")

출력

File closed.
Traceback (most recent call last):
   File "C:/Python/Python361/finally_try_except1.py", line 4, in <module>
      file.write(4)
TypeError: write() argument must be str, not int

따라서 위에서 보면 마지막으로 예외 발생 여부에 관계없이 절이 항상 실행되는 것을 볼 수 있습니다.