คุณสามารถใช้บล็อก finally ร่วมกับบล็อก try บล็อก finally เป็นที่วางโค้ดที่ต้องดำเนินการเสมอ ไม่ว่าบล็อก try จะ raise ข้อยกเว้นหรือไม่ ไวยากรณ์ของคำสั่ง try-finally คือ:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
คุณไม่สามารถใช้ clause else ร่วมกับ finally clause ได้
ตัวอย่าง
#!/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"
ผลลัพธ์ (Output)
หากคุณไม่มีสิทธิ์เปิดไฟล์ในโหมดเขียน จะได้ผลลัพธ์ดังนี้:
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"
เมื่อข้อยกเว้นถูกโยนในบล็อก try การดำเนินการจะส่งต่อไปยังบล็อก finally ทันที หลังจากคำสั่งทั้งหมดในบล็อก finally ถูกดำเนินการ ข้อยกเว้นจะถูก raise อีกครั้งและจัดการในคำสั่ง except หากมีในเลเยอร์ try-except ถัดไปที่สูงกว่า