Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การกำหนด Clean Up Actions ใน Python (Finally)


มีสถานการณ์มากมายที่เราต้องการให้โปรแกรมทำงานเฉพาะเจาะจง ไม่ว่าจะรันสำเร็จหรือโยนข้อผิดพลาด ส่วนใหญ่เพื่อจับข้อผิดพลาดหรือข้อยกเว้น เราใช้ try และ except block

คำสั่ง "try" ให้ optional clause ที่มีประโยชน์มาก ซึ่งใช้สำหรับกำหนด 'clean-up actions' ที่ต้องรันภายใต้สภาพแวดล้อมใดๆ ตัวอย่าง −

>>> try:     raise SyntaxError finally:     print("Learning Python!") Learning Python! Traceback (most recent call last):   File "", line 2, in      raise SyntaxError   File "", line None SyntaxError: 

Finally clause จะรันเสมอไม่ว่าจะเกิดอะไรขึ้น อย่างไรก็ตาม else clause รันก็ต่อเมื่อไม่มีข้อยกเว้นถูกยกขึ้น

ตัวอย่าง 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 − ลองทำให้เกิดข้อยกเว้นโดยทำให้ไฟล์เป็น read-only และพยายามเขียนลงไป จึงทำให้เกิดข้อยกเว้น

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.

ในกรณีที่เรามีข้อผิดพลาด แต่เราไม่ได้ใส่ except clause เพื่อจัดการ ในกรณีเช่นนี้ clean-up action (finally block) จะถูกรันก่อน แล้วค่อย error ถูกยกขึ้นโดยคอมไพเลอร์ มาเข้าใจแนวคิดกับตัวอย่างด้านล่าง −

ตัวอย่าง

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      file.write(4) TypeError: write() argument must be str, not int

ดังนั้นจากข้างต้น เราเห็นได้ว่า finally clause รันเสมอ ไม่ว่าจะมีข้อยกเว้นเกิดขึ้นหรือไม่ก็ตาม