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: ตัวอย่างนี้จับการหารด้วยศูนย์

[1]
[output]
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 ที่รันเมื่อมีข้อผิดพลาด)

[2]
[output]
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 จะสำเร็จหรือเกิดข้อผิดพลาด เหมาะกับงานปิดท้าย เช่น แจ้งว่าจบขั้นตอนแล้ว

[3]
[output]
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: เพื่อจับเฉพาะประเภทนั้น

[4]
[output]
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()

[5]
[output]
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 ข้อผิดพลาดที่พบบ่อย

  1. A bare except:. It catches every error, including your own typing mistakes, and hides real bugs. Name the error you expect, such as except ValueError:.
  2. except: เปล่า ๆ จะจับทุก error รวมถึงความผิดพลาดจากการพิมพ์ของคุณเอง ทำให้บั๊กจริงถูกซ่อน ควรระบุชนิด error ที่คาดไว้ เช่น except ValueError:
  3. Too much code inside try. When a line fails, the rest of the try block is skipped (the demo never prints never printed). Put only the risky line in try so you know what the except is really protecting.
  4. ใส่โค้ดใน try มากเกินไป เมื่อบรรทัดหนึ่งเกิด error โค้ดที่เหลือในบล็อก try จะถูกข้าม (ตัวอย่างจะไม่พิมพ์ never printed) ควรใส่เฉพาะบรรทัดที่เสี่ยงไว้ใน try จะได้รู้ว่า except ป้องกันอะไรอยู่
  5. Catching an error and doing nothing. except ZeroDivisionError: pass hides the problem completely. At least print a message so you can see that something went wrong.
  6. จับ error แล้วไม่ทำอะไร except ZeroDivisionError: pass ซ่อนปัญหาไปเลย อย่างน้อยควรพิมพ์ข้อความเพื่อให้รู้ว่ามีบางอย่างผิดพลาด
[7]
[output]
start
caught
cleanup

8 Think further 8 แบบฝึกคิดต่อ

Try these yourself in the Run boxes above (or in Google Colab):

ลองทำเองในกล่อง Run ด้านบน (หรือใน Google Colab):

  1. Catch both ValueError and ZeroDivisionError with two except blocks that print different messages.
  2. จับทั้ง ValueError และ ZeroDivisionError ด้วย except สองบล็อกที่พิมพ์ข้อความต่างกัน
  3. Add an else block that prints the result only when no error happened. How is that different from putting the print at the end of try?
  4. เพิ่มบล็อก else ที่พิมพ์ผลลัพธ์เฉพาะเมื่อไม่มี error ต่างจากการวาง print ไว้ท้าย try อย่างไร
  5. Try converting "12", "3.5" and "" with int(). Which ones raise ValueError?
  6. ลองแปล "12", "3.5" และ "" ด้วย int() ค่าไหนทำให้เกิด ValueError

Key takeaways สรุปสำคัญ

Remember these points when you write your own programs:

จำประเด็นเหล่านี้ไว้เมื่อเขียนโปรแกรมของคุณเอง:

  1. Wrap only the risky step in try and name the exact error in except.
  2. ครอบเฉพาะขั้นตอนที่เสี่ยงด้วย try และระบุชนิด error ให้ชัดใน except
  3. else holds the code that should run only when nothing went wrong; finally runs in every case and is meant for clean-up.
  4. else ใส่โค้ดที่ต้องรันเมื่อไม่มีอะไรผิดพลาดเท่านั้น ส่วน finally รันทุกกรณีและเหมาะกับงานเก็บกวาด
  5. 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.
  6. error ที่จับแล้วเพิกเฉยแย่กว่า error ที่ทำให้โปรแกรมหยุด เพราะไม่มีใครรู้ ควรแสดงข้อความหรือบันทึกไว้
  7. Handling errors is not a replacement for checking the input: test what you can (for example a count of zero) and use try for what you cannot predict.
  8. การจัดการ 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:

แหล่งที่ใช้ประกอบเนื้อหาในบทนี้:

  1. Errors and Exceptions — Python Tutorial — Errors and Exceptions (try / except / else / finally)

End-of-lesson quizแบบฝึกหัดท้ายบท

ตอบแล้ว 0 / 10

ข้อ 1

1 / 10

What kind of code goes in a try block?บล็อก try ใช้วางโค้ดแบบใด?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (A) Code that might raise an errorโค้ดที่อาจเกิดข้อผิดพลาด

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) Code that might raise an errorโค้ดที่อาจเกิดข้อผิดพลาด
    Correct! Put risky code in try.ถูกต้อง! วางโค้ดเสี่ยงไว้ใน try
  • (B) Only function definitionsเฉพาะการประกาศฟังก์ชันเท่านั้น
    Wrong: try is not limited to function definitions.ผิด: try ไม่จำกัดแค่ประกาศฟังก์ชัน
  • (C) Only for loopsเฉพาะการวนลูป for
    Wrong: for is a different structure from try.ผิด: for อยู่คนละโครงสร้างกับ try
  • (D) Only printing textเฉพาะการพิมพ์ข้อความ
    Wrong: any statement that could fail can go there.ผิด: วางคำสั่งใดก็ได้ที่อาจพังได้

ข้อ 2

2 / 10

When does finally run?finally รันเมื่อใด?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (C) Always, whether the try succeeded or raised an errorเสมอ ไม่ว่า try จะสำเร็จหรือเกิดข้อผิดพลาด

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) Only when there is an exceptionเฉพาะเมื่อมี exception
    Wrong: finally does not run only on an error.ผิด: finally ไม่ได้รันเฉพาะตอนมี error
  • (B) Only when there is no exceptionเฉพาะเมื่อไม่มี exception
    Wrong: that is closer to the else of try.ผิด: นั่นใกล้เคียง else ของ try มากกว่า
  • (C) Always, whether the try succeeded or raised an errorเสมอ ไม่ว่า try จะสำเร็จหรือเกิดข้อผิดพลาด
    Correct! finally always runs.ถูกต้อง! finally ทำงานเสมอ
  • (D) Only when the computer shuts downเฉพาะตอนโปรแกรมปิดเครื่อง
    Wrong: it has nothing to do with shutdown.ผิด: ไม่เกี่ยวกับการปิดเครื่อง

ข้อ 3

3 / 10

When does the else of a try structure run?else ของโครงสร้าง try รันเมื่อใด?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (B) When try had no exceptionเมื่อ try ไม่มี exception

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) When an exception occurs in tryเมื่อเกิด exception ใน try
    Wrong: with an exception, control goes to except, not else.ผิด: ตอนมี exception จะไป except ไม่ใช่ else
  • (B) When try had no exceptionเมื่อ try ไม่มี exception
    Correct! The else of a try runs when there was no error.ถูกต้อง! else ของ try รันเมื่อไม่มีข้อผิดพลาด
  • (C) It always replaces finallyแทนที่ finally เสมอ
    Wrong: else and finally are different blocks.ผิด: else กับ finally เป็นคนละบล็อก
  • (D) Only when there is a break in a loopเมื่อมี break ในลูปเท่านั้น
    Wrong: it has nothing to do with break.ผิด: ไม่เกี่ยวกับ break

ข้อ 4

4 / 10

With try: print(1/0) then except: print("e"), what happens?จาก try: print(1/0) แล้ว except: print("e") จะเกิดอะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (D) except runs and prints eเข้า except แล้วพิมพ์ e

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) It prints the division result and endsพิมพ์ผลหารแล้วจบ
    Wrong: dividing by zero errors before printing a result.ผิด: หารด้วยศูนย์เกิดข้อผิดพลาดก่อนพิมพ์ผล
  • (B) The program hangs foreverโปรแกรมค้างไม่รู้จบ
    Wrong: there is no loop.ผิด: ไม่ได้วนลูป
  • (C) It skips except entirelyข้าม except ไปเลย
    Wrong: there is an error, so except runs.ผิด: มีข้อผิดพลาดจึงเข้า except
  • (D) except runs and prints eเข้า except แล้วพิมพ์ e
    Correct! The division by zero is caught by except.ถูกต้อง! หารด้วยศูนย์ถูกจับด้วย except

ข้อ 5

5 / 10

How does except ZeroDivisionError: differ from a bare except:?except ZeroDivisionError: ต่างจาก except: อย่างไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (A) It catches only division-by-zero errorsจับเฉพาะข้อผิดพลาดประเภทหารด้วยศูนย์

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) It catches only division-by-zero errorsจับเฉพาะข้อผิดพลาดประเภทหารด้วยศูนย์
    Correct! Naming a type catches only that type.ถูกต้อง! ระบุชื่อประเภทเพื่อจับเฉพาะนั้น
  • (B) It catches every error exactly the sameจับทุกข้อผิดพลาดเหมือนกันทุกประการ
    Wrong: a bare except is broader; naming a type is narrower.ผิด: bare except กว้างกว่า การระบุชื่อแคบกว่า
  • (C) It cannot be used with finallyห้ามใช้คู่กับ finally
    Wrong: it works fine with finally.ผิด: ใช้คู่กับ finally ได้
  • (D) It works only inside a while loopใช้ได้เฉพาะในลูป while
    Wrong: it is not limited to while.ผิด: ไม่จำกัดเฉพาะ while

ข้อ 6

6 / 10

With try: print(10/2) / except: print("error") / else: print("no error"), what is printed?จาก try: print(10/2) / except: print("error") / else: print("no error") จะพิมพ์อะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (B) 5.0 then no error5.0 แล้วตามด้วย no error

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) errorerror
    Wrong: 10/2 does not raise an error.ผิด: 10/2 ไม่เกิดข้อผิดพลาด
  • (B) 5.0 then no error5.0 แล้วตามด้วย no error
    Correct! try succeeds (prints 5.0), then else runs.ถูกต้อง! try สำเร็จ (พิมพ์ 5.0) แล้ว else รัน
  • (C) Only no errorno error อย่างเดียว
    Wrong: the print(10/2) line runs too.ผิด: บรรทัด print(10/2) ก็ทำงานด้วย
  • (D) Nothingไม่พิมพ์อะไร
    Wrong: both try and else print.ผิด: ทั้ง try และ else พิมพ์

ข้อ 7

7 / 10

With try: print(1/0) / except ZeroDivisionError: print("cannot divide by zero") / finally: print("done"), what is printed?จาก try: print(1/0) / except ZeroDivisionError: print("cannot divide by zero") / finally: print("done") จะพิมพ์อะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (D) cannot divide by zero then donecannot divide by zero แล้วตามด้วย done

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) Only donedone อย่างเดียว
    Wrong: except prints too.ผิด: except ก็พิมพ์ด้วย
  • (B) Only cannot divide by zerocannot divide by zero อย่างเดียว
    Wrong: finally always runs, so done also prints.ผิด: finally รันเสมอ จึงพิมพ์ done ด้วย
  • (C) Nothing, because an error occurredไม่พิมพ์อะไร เพราะเกิด error
    Wrong: the error is caught by except.ผิด: error ถูกจับด้วย except
  • (D) cannot divide by zero then donecannot divide by zero แล้วตามด้วย done
    Correct! except catches the error, then finally runs.ถูกต้อง! except จับ error แล้ว finally รันต่อ

ข้อ 8

8 / 10

Why is try / except useful?ทำไม try / except จึงมีประโยชน์?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (C) It keeps the program from crashing on an error and lets it carry onช่วยให้โปรแกรมไม่หยุดกลางคันเมื่อเกิดข้อผิดพลาด และจัดการต่อได้

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) It always makes the program run fasterทำให้โปรแกรมทำงานเร็วขึ้นเสมอ
    Wrong: it is not about speed.ผิด: ไม่ได้เกี่ยวกับความเร็วโดยตรง
  • (B) It removes bugs from the code automaticallyลบข้อผิดพลาดออกจากโค้ดโดยอัตโนมัติ
    Wrong: it handles runtime errors; it does not fix the code.ผิด: มันจัดการ error ตอนรัน ไม่ได้แก้โค้ดให้
  • (C) It keeps the program from crashing on an error and lets it carry onช่วยให้โปรแกรมไม่หยุดกลางคันเมื่อเกิดข้อผิดพลาด และจัดการต่อได้
    Correct! It catches the error and handles it safely.ถูกต้อง! จับ error แล้วจัดการอย่างปลอดภัย
  • (D) It makes every function return Noneทำให้ทุกฟังก์ชันคืนค่า None
    Wrong: it has nothing to do with return values.ผิด: ไม่เกี่ยวกับค่าที่ฟังก์ชันคืน

ข้อ 9

9 / 10

If you write try: with neither except nor finally, what happens?ถ้าเขียน try: โดยไม่มีทั้ง except และ finally จะเกิดอะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (B) A SyntaxError, because try needs an except or finallyเกิด SyntaxError เพราะ try ต้องมี except หรือ finally

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) It works fine with no problemทำงานปกติ ไม่มีปัญหา
    Wrong: a try needs at least one of except or finally.ผิด: try ต้องมี except หรือ finally อย่างน้อยหนึ่ง
  • (B) A SyntaxError, because try needs an except or finallyเกิด SyntaxError เพราะ try ต้องมี except หรือ finally
    Correct! A lone try is invalid syntax.ถูกต้อง! try เดี่ยวๆ ไม่ถูกไวยากรณ์
  • (C) The program silently skips the try blockโปรแกรมข้ามบล็อก try ไปเงียบๆ
    Wrong: it does not skip silently; it is a syntax error.ผิด: ไม่ได้ข้ามเงียบๆ แต่เป็นข้อผิดพลาดไวยากรณ์
  • (D) An except is added automaticallyexcept ถูกเพิ่มให้อัตโนมัติ
    Wrong: Python does not add an except for you.ผิด: Python ไม่เติม except ให้

ข้อ 10

10 / 10

What is the run order when try raises a caught exception and there is a finally?ลำดับการทำงานเมื่อ try เกิด exception ที่ถูกจับ และมี finally คือข้อใด?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (C) Run except (handle the error), then finallyรัน except (จัดการ error) แล้วตามด้วย finally

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) finally first, then exceptfinally ก่อน แล้วค่อย except
    Wrong: except handles the error first, then finally closes out.ผิด: except จัดการ error ก่อน แล้ว finally ปิดท้าย
  • (B) except only, skipping finallyexcept อย่างเดียว ข้าม finally
    Wrong: finally always runs.ผิด: finally รันเสมอ
  • (C) Run except (handle the error), then finallyรัน except (จัดการ error) แล้วตามด้วย finally
    Correct! except handles it first, then finally always closes out.ถูกต้อง! except จัดการก่อน finally ปิดท้ายเสมอ
  • (D) Skip both except and finallyข้ามทั้ง except และ finally
    Wrong: both run.ผิด: ทั้งคู่ทำงาน