주어진 코드에서 수퍼 클래스 Exception의 하위 클래스인 사용자 정의 예외 FooException이 생성되었습니다. 다음과 같이 사용자 지정 예외에 문자열 개체를 전달합니다.
예시
#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 이 스크립트가 다음과 같이 터미널에서 실행되면
$ python foobar.py
문자열을 입력하면 다음을 얻습니다.
출력
"C:/Users/TutorialsPoint1/~foobar.py" Enter a string:'voila' <type 'str'> Voila