try / except / finally: handling errors Try / Except / Finally: จัดการข้อผิดพลาด
Put risky code in try, catch it with except, and use finally for work that must always run
วางโค้ดเสี่ยงไว้ใน try จับด้วย except และใช้ finally สำหรับงานที่ต้องทำเสมอ
When a program hits an error (an exception), it may stop immediately. The try / except
structure catches the error so you can handle it safely and carry on. finally always runs, and the
else of a try runs only when there was no exception.
เมื่อโปรแกรมเจอข้อผิดพลาด (exception) อาจหยุดทำงานทันที
โครงสร้าง try / except ช่วยจับข้อผิดพลาดแล้วจัดการต่อได้อย่างปลอดภัย
ส่วน finally รันเสมอ และ else ของ try รันเมื่อไม่มี exception
1 Basic try / except 1 try / except พื้นฐาน
Code that might fail goes in try: — if an error occurs, control jumps to except:.
This example catches a division by zero.
โค้ดที่อาจพังอยู่ใน try: — ถ้าเกิดข้อผิดพลาดจะกระโดดไป except:
ตัวอย่างนี้จับการหารด้วยศูนย์
caught error
2 try / except / else
else: after except runs when the try block had no exception (unlike
except, which runs when there was an error).
else: หลัง except จะรันเมื่อบล็อก try ไม่มี exception
(ต่างจาก except ที่รันเมื่อมีข้อผิดพลาด)
5.0 no error
3 try / finally
finally: always runs, whether the try succeeded or raised an error. It suits
closing-up work, such as reporting that a step is done.
finally: รันเสมอ ไม่ว่า try จะสำเร็จหรือเกิดข้อผิดพลาด
เหมาะกับงานปิดท้าย เช่น แจ้งว่าจบขั้นตอนแล้ว
working always runs
4 try / except / finally together 4 try / except / finally รวมกัน
Catch the error in except while still running finally afterwards, every time. You can name a type, e.g.
except ZeroDivisionError:, to catch only that kind.
จับข้อผิดพลาดใน except แล้วยังให้ finally ทำงานต่อท้ายเสมอ
สามารถระบุชื่อเช่น except ZeroDivisionError: เพื่อจับเฉพาะประเภทนั้น
cannot divide by zero done
5 An average with no data 5 ค่าเฉลี่ยเมื่อยังไม่มีข้อมูล
A report that divides a total by a count fails when the count is zero — for example on the first day, before any marks are entered. Catching ZeroDivisionError lets the program show a friendly message instead of crashing. The same idea protects any risky step, such as converting user text with int().
รายงานที่หารยอดรวมด้วยจำนวนจะพังเมื่อจำนวนเป็นศูนย์ เช่น วันแรกที่ยังไม่มีคะแนนเลย การดัก ZeroDivisionError ทำให้โปรแกรมแสดงข้อความที่เข้าใจง่ายแทนที่จะพัง แนวคิดเดียวกันใช้ป้องกันขั้นตอนเสี่ยงอื่น ๆ ได้ เช่น การแปลงข้อความของผู้ใช้ด้วย int()
No marks yet Cannot divide by zero
6 Which block runs when? 6 บล็อกไหนรันเมื่อไร
| Situationสถานการณ์ | try |
except |
else |
finally |
|---|---|---|---|---|
| No errorไม่มี error | ✓ | – | ✓ | ✓ |
| Error that is caughtมี error ที่จับได้ | until the errorจนถึงจุดที่ error | ✓ | – | ✓ |
| Error that is not caughtมี error ที่จับไม่ได้ | until the errorจนถึงจุดที่ error | – | – | ✓ |
return inside tryreturn ใน try |
✓ | – | – | ✓ |
finally is the only block that runs in every row — that is why it is used for clean-up such as closing a file.
finally เป็นบล็อกเดียวที่รันในทุกกรณี จึงใช้สำหรับงานเก็บกวาด เช่น ปิดไฟล์
7 Common mistakes 7 ข้อผิดพลาดที่พบบ่อย
-
A bare
except:. It catches every error, including your own typing mistakes, and hides real bugs. Name the error you expect, such asexcept ValueError:. -
except:เปล่า ๆ จะจับทุก error รวมถึงความผิดพลาดจากการพิมพ์ของคุณเอง ทำให้บั๊กจริงถูกซ่อน ควรระบุชนิด error ที่คาดไว้ เช่นexcept ValueError: -
Too much code inside
try. When a line fails, the rest of thetryblock is skipped (the demo never printsnever printed). Put only the risky line intryso you know what theexceptis really protecting. -
ใส่โค้ดใน
tryมากเกินไป เมื่อบรรทัดหนึ่งเกิด error โค้ดที่เหลือในบล็อกtryจะถูกข้าม (ตัวอย่างจะไม่พิมพ์never printed) ควรใส่เฉพาะบรรทัดที่เสี่ยงไว้ในtryจะได้รู้ว่าexceptป้องกันอะไรอยู่ -
Catching an error and doing nothing.
except ZeroDivisionError: passhides the problem completely. At least print a message so you can see that something went wrong. -
จับ error แล้วไม่ทำอะไร
except ZeroDivisionError: passซ่อนปัญหาไปเลย อย่างน้อยควรพิมพ์ข้อความเพื่อให้รู้ว่ามีบางอย่างผิดพลาด
start caught cleanup
8 Think further 8 แบบฝึกคิดต่อ
Try these yourself in the Run boxes above (or in Google Colab):
ลองทำเองในกล่อง Run ด้านบน (หรือใน Google Colab):
-
Catch both
ValueErrorandZeroDivisionErrorwith twoexceptblocks that print different messages. -
จับทั้ง
ValueErrorและZeroDivisionErrorด้วยexceptสองบล็อกที่พิมพ์ข้อความต่างกัน -
Add an
elseblock that prints the result only when no error happened. How is that different from putting theprintat the end oftry? -
เพิ่มบล็อก
elseที่พิมพ์ผลลัพธ์เฉพาะเมื่อไม่มี error ต่างจากการวางprintไว้ท้ายtryอย่างไร -
Try converting
"12","3.5"and""withint(). Which ones raiseValueError? -
ลองแปล
"12","3.5"และ""ด้วยint()ค่าไหนทำให้เกิดValueError
Key takeaways สรุปสำคัญ
Remember these points when you write your own programs:
จำประเด็นเหล่านี้ไว้เมื่อเขียนโปรแกรมของคุณเอง:
-
Wrap only the risky step in
tryand name the exact error inexcept. -
ครอบเฉพาะขั้นตอนที่เสี่ยงด้วย
tryและระบุชนิด error ให้ชัดในexcept -
elseholds the code that should run only when nothing went wrong;finallyruns in every case and is meant for clean-up. -
elseใส่โค้ดที่ต้องรันเมื่อไม่มีอะไรผิดพลาดเท่านั้น ส่วนfinallyรันทุกกรณีและเหมาะกับงานเก็บกวาด - An error you catch and ignore is worse than an error that stops the program, because nobody will notice it. Show a message or record it.
- error ที่จับแล้วเพิกเฉยแย่กว่า error ที่ทำให้โปรแกรมหยุด เพราะไม่มีใครรู้ ควรแสดงข้อความหรือบันทึกไว้
-
Handling errors is not a replacement for checking the input: test what you can (for example a count of zero) and use
tryfor what you cannot predict. -
การจัดการ error ไม่ได้แทนการตรวจข้อมูลนำเข้า ตรวจสิ่งที่ตรวจได้ก่อน (เช่น จำนวนเป็นศูนย์) แล้วใช้
tryกับสิ่งที่คาดเดาไม่ได้
Note: Run on this page is a JavaScript simulation, not real Python. For real Python, try Google Colab. หมายเหตุ: การกด Run บนหน้านี้เป็นการจำลองด้วย JavaScript ไม่ใช่ Python จริง หากต้องการทดลอง Python จริง แนะนำ Google Colab
References References / แหล่งอ้างอิง
Sources used for this lesson:
แหล่งที่ใช้ประกอบเนื้อหาในบทนี้:
-
Errors and Exceptions —
Python Tutorial — Errors and Exceptions
(
try/except/else/finally)