Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

การจัดการข้อยกเว้น


เมื่อเขียนโปรแกรม, ข้อผิดพลาดเกิดขึ้นเป็นเรื่องปกติในชีวิต อาจจะเป็นเพราะผู้ใช้ใส่ข้อมูลผิดพลาด หรือตัวทรัพยากรเครือข่ายไม่สามารถใช้งานได้ อาจจะเพราะโปรแกรมใช้หน่วยความจำหมด หรืออาจจะเป็นเพราะโปรแกรมเมอร์ทำผิดพลาด!

ทางแก้ไขข้อผิดพลาดใน Python คือข้อยกเว้น (exceptions) คุณอาจจะเคยเห็นข้อยกเว้นมาก่อน

print(a)

#error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

โอ๊ะ! ลืมกำหนดค่าให้ตัวแปร 'a'

แต่บางครั้งคุณไม่ต้องการให้ข้อยกเว้นมาหยุดโปรแกรมทั้งหมด คุณอาจจะต้องการทำบางสิ่งบางอย่างพิเศษเมื่อมีการยกข้อยกเว้นขึ้นมา ซึ่งสามารถทำได้ในบล็อก try/except

นี่คือตัวอย่างง่ายๆ: สมมติว่าคุณกำลังวนซ้ำในรายการ คุณต้องการวนซ้ำผ่าน 20 ตัวเลข แต่รายการนี้มาจากการใส่ข้อมูลของผู้ใช้ และอาจจะไม่มี 20 ตัวเลขในรายการ หลังจากที่คุณวนจนถึงจุดสิ้นสุดของรายการ คุณเพียงต้องการให้ตัวเลขที่เหลือถูกตีความเป็น 0 นี่คือวิธีที่คุณสามารถทำได้:

def do_stuff_with_number(n):
    print(n)

def catch_this():
    the_list = (1, 2, 3, 4, 5)

    for i in range(20):
        try:
            do_stuff_with_number(the_list[i])
        except IndexError: # Raised when accessing a non-existing index of a list
            do_stuff_with_number(0)

catch_this()

เห็นไหม ไม่ยากเลย! คุณสามารถทำแบบนี้กับข้อยกเว้นใดๆ ได้ สำหรับรายละเอียดเพิ่มเติมเกี่ยวกับการจัดการข้อยกเว้น ดูได้ที่ เอกสาร Python

Exercise

จัดการข้อยกเว้นทั้งหมด! ลองย้อนกลับไปคิดถึงบทเรียนก่อนหน้าเพื่อคืนค่านามสกุลของนักแสดง

# Setup actor = {"name": "John Cleese", "rank": "awesome"} # Function to modify!!! def get_last_name(): return actor["last_name"] # Test code get_last_name() print("All exceptions caught! Good job!") print("The actor's last name is %s" % get_last_name()) actor = {"name": "John Cleese", "rank": "awesome"} def get_last_name(): return actor["name"].split()[1] get_last_name() print("All exceptions caught! Good job!") print("The actor's last name is %s" % get_last_name()) test_output_contains("Cleese") test_output_contains("All exceptions caught! Good job!") test_output_contains("The actor's last name is Cleese") success_msg("Great work!")

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy