当我在类中创建 try-except 时,如图所示出现错误:(在类中创建基于用户的异常的原因是,我可以在需要时在任何函数中重新使用异常,并且可以引发错误)
class Error(Exception):
pass
class ValueTooSmallError(Error):
pass
class ValueTooLargeError(Error):
pass
import random
class GuessNum(object):
try:
def __init__(self):
self.number = random.randint(1,50)
def startGame(self):
while True:
i_num = int(input("Enter a number: "))
if i_num < self.number:
raise ValueTooSmallError
elif i_num > self.number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()
但是,当我在函数脚本中创建 try-except 时工作正常,但想知道为什么上面的脚本失败了。请指教。
number = 10
while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()
print("Congratulations! You guessed it correctly.")