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

วิธี Manual Throw/Raise Exception ใน Python

ใช้ raise กับ specific exception constructor

ตัวอย่าง

import sys

try:
    f = float('Tutorialspoint')
    print(f)
    raise ValueError
except Exception as err:
    print(sys.exc_info())

ผลลัพธ์

(, ValueError('could not convert string to float: Tutorialspoint',), )

Raise พร้อม arguments:

try:
    raise ValueError('foo', 23)
except ValueError as e:
    print(e.args)

ผลลัพธ์

('foo', 23)

Best practice: Raise specific exceptions ไม่ใช่ generic Exception