คุณสามารถใช้ ในที่สุด :บล็อกพร้อมกับ ลอง :บล็อก. บล็อกสุดท้ายเป็นที่สำหรับวางโค้ดใด ๆ ที่ต้องดำเนินการ ไม่ว่า try-block จะมีข้อยกเว้นหรือไม่ก็ตาม ไวยากรณ์ของคำสั่ง try-finally คือ −
try: You do your operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed. ......................
คุณไม่สามารถใช้ส่วนประโยคอื่นร่วมกับประโยคสุดท้ายได้
ตัวอย่าง
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data" ผลลัพธ์
หากคุณไม่ได้รับอนุญาตให้เปิดไฟล์ในโหมดเขียน สิ่งนี้จะทำให้เกิดผลลัพธ์ดังต่อไปนี้ -
Error: can't find file or read data
ตัวอย่างเดียวกันสามารถเขียนได้ชัดเจนยิ่งขึ้นดังนี้ −
ตัวอย่าง
#!/usr/bin/python
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data" เมื่อมีการส่งข้อยกเว้นในบล็อกการลอง การดำเนินการจะส่งผ่านไปยังบล็อกสุดท้ายทันที หลังจากที่ดำเนินการคำสั่งทั้งหมดในบล็อกสุดท้ายแล้ว ข้อยกเว้นจะถูกยกขึ้นอีกครั้งและจะได้รับการจัดการในคำสั่งยกเว้น ถ้ามีอยู่ในเลเยอร์ที่สูงกว่าถัดไปของคำสั่งพยายามยกเว้น