编写程序接收用户输入分数信息,如果分数在0—100之间,输出成绩。如果成绩不在该范围内,抛出异常信息,提示分数必须在0—100之间。使用自定义异常实现
时间: 2024-05-05 16:22:34 浏览: 16
以下是实现该功能的 Python 代码:
```python
class ScoreError(Exception): # 自定义异常类
def __init__(self, score):
self.score = score
def __str__(self):
return f"Invalid score: {self.score}. Score must be between 0 and 100."
def get_score():
score = int(input("Please enter your score: "))
if score < 0 or score > 100:
raise ScoreError(score) # 抛出自定义异常
else:
print(f"Your score is {score}.")
if __name__ == "__main__":
try:
get_score()
except ScoreError as se:
print(se)
```
在这个程序中,我们定义了一个自定义异常类 `ScoreError`,并在 `get_score` 函数中判断输入的分数是否在0—100之间。如果分数不在该范围内,就抛出 `ScoreError` 异常。在程序的主函数中,我们使用 `try-except` 语句捕获该异常并输出错误信息。
运行程序时,如果输入的分数不在0—100之间,就会抛出自定义异常,输出类似于 "Invalid score: 120. Score must be between 0 and 100." 的错误信息。如果输入的分数在该范围内,就会输出成绩。