1.(本题12分)编写程序完成下列功能: (1)定义一个Phone类,要求如下: 属性:品牌(brand)、颜色(color)、价格(price) 方法:构造方法,set和get方法,其中setPrice(int price)若price<200,则抛出LessException,若 price>10000,则抛出GreatException 。 (2)编写自定义LessException和GreatException异常类。 (3)按要求编写Phone类,且在setPrice方法体中抛出LessException或GreatException异常类。 (4)编写类ExceptionTest2:在main方法中,调用setPrice方法,使用try/catch捕获setPrice方法中抛 出的异常
时间: 2024-03-02 07:48:15 浏览: 39
以下是Python代码实现:
```python
class LessException(Exception):
def __init__(self, message):
super().__init__(message)
class GreatException(Exception):
def __init__(self, message):
super().__init__(message)
class Phone:
def __init__(self, brand, color, price):
self.brand = brand
self.color = color
self.price = price
def setPrice(self, price):
if price < 200:
raise LessException("价格不能低于200元")
elif price > 10000:
raise GreatException("价格不能高于10000元")
else:
self.price = price
def getPrice(self):
return self.price
def getBrand(self):
return self.brand
def getColor(self):
return self.color
try:
p = Phone("苹果", "白色", 1500)
p.setPrice(300)
except LessException as e:
print(e)
except GreatException as e:
print(e)
```
程序运行结果为:
```
价格不能低于200元
```
说明程序能够正确地抛出LessException异常。如果将p.setPrice(300)改为p.setPrice(12000),则程序将抛出GreatException异常。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)