Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเขียน Try/Except Catch ทุก Python Exceptions

Rule of thumb: ไม่ควร catch ทุกอย่าง (bare except) เพราะจะจับ KeyboardInterrupt, SystemExit ด้วย

ไม่แนะนำ

try:
    # do_something()
except:
    print("Exception Caught!")

แนะนำ: Catch specific exceptions + bare except พร้อม re-raise

try:
    f = open('file.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print("I/O error({0}): {1}".format(errno, strerror))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

ผลลัพธ์ (ถ้า file.txt ไม่มี)

I/O error(2): No such file or directory