Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách raise exception trong Python?

Chúng ta có thể force raise exception dùng từ khóa raise. Đây là syntax gọi method raise:

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

trong đó, Exception là tên exception; args tùy chọn đại diện cho value của exception argument.

Cũng optional argument, traceback, là traceback object dùng cho exception.

# raise_error.py
try:
    i = int(input("Nhập giá trị nguyên dương: "))
    if i <= 0:
        raise ValueError("Đây không phải số dương!!")
except ValueError as e:
    print(e)

Nếu chúng ta execute script trên tại terminal như sau:

$ python raise_error.py
Enter a positive integer: -6

Sau đây hiển thị vì chúng ta nhập số âm:

Đây không phải số dương!!

Alternate example code

# Here there is no variable or argument passed with the raised exception
import sys
try:
    i = int(input("Nhập giá trị nguyên dương: "))
    if i <= 0:
        raise ValueError  # ("Đây không phải số dương!!")
except ValueError as e:
    print(sys.exc_info())

output

Enter a positive integer value: -9
(<type 'exceptions.ValueError'>, ValueError(), <traceback object at 0x0000000003584EC8>)