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

วิธี Raise Exception ใน Python

ใช้ keyword raise

Syntax

raise [Exception [, args [, traceback]]]

ตัวอย่าง: Raise ValueError ถ้า input ไม่ใช่ positive integer

# raise_error.py
try:
    i = int(input("Enter a positive integer value: "))
    if i <= 0:
        raise ValueError("This is not a positive number!!")
except ValueError as e:
    print(e)

รัน: $ python raise_error.py Input: -6

This is not a positive number!!

Raise โดยไม่มี argument

try:
    i = int(input("Enter a positive integer value: "))
    if i <= 0:
        raise ValueError
except ValueError as e:
    print(sys.exc_info())