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

Cách đúng để pass object với custom exception trong Python?

Trong code cho trước, custom exception FooException đã được tạo là subclass của super class Exception. Chúng ta sẽ pass string object cho custom exception như sau:

Ví dụ

# foobar.py
class FooException(Exception):
    def __init__(self, text, *args):
        super(FooException, self).__init__(text, *args)
        self.text = text

try:
    bar = input("Enter a string:")
    if not isinstance(bar, basestring):
        raise FooException(bar)
except FooException as r:
    print('there is an error')
else:
    print(type(bar))
    print(bar)

Nếu script này chạy tại terminal như sau chúng ta nhận được:

$ python foobar.py

Chúng ta nhận được sau nếu nhập string:

Kết quả

"C:/Users/TutorialsPoint1/~foobar.py"
Enter a string:'voila'
<type 'str'>
Voila