Computer >> Máy Tính >  >> Lập trình >> Python

Làm thế nào để nâng cao một ngoại lệ trong Python?


Chúng tôi có thể buộc tăng một ngoại lệ bằng cách sử dụng từ khóa raise. Đây là cú pháp để gọi phương thức "raise".

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

trong đó, Exception là tên của ngoại lệ; “args” tùy chọn đại diện cho giá trị của đối số ngoại lệ.

Đối số cũng tùy chọn, theo dõi lại, là đối tượng theo dõi được sử dụng cho ngoại lệ.


#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)


Nếu chúng ta thực thi đoạn mã trên tại terminal như sau

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

Thông tin sau được hiển thị vì chúng tôi đã nhập một số âm:

This is not a positive number!!

Mã mẫu thay thế

# Here there is no variable or argument passed with the raised exception
import sys
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 sys.exc_info()

đầu ra

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