编写自定义LessException和 GreatException异常类。 编写Phone类,在setPrice方法体中抛出 LessException或GreatException异常类 编写类ExceptionTest3: 在main()方法中,调用setPrice方法,使用 try/catch捕获setPrice方法中抛出的异常。
时间: 2024-02-29 08:51:59 浏览: 23
好的,以下是自定义的LessException和GreatException异常类的定义:
```java
// 自定义异常类LessException
class LessException extends Exception {
public LessException(String message) {
super(message);
}
}
// 自定义异常类GreatException
class GreatException extends Exception {
public GreatException(String message) {
super(message);
}
}
```
接下来是Phone类的定义,其中setPrice方法中会抛出LessException或GreatException异常:
```java
public class Phone {
private String brand; // 品牌
private int price; // 价格
// 构造方法
public Phone(String brand, int price) {
this.brand = brand;
this.price = price;
}
// 品牌的get和set方法
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
// 价格的get和set方法,若价格不符合要求则抛出异常
public int getPrice() {
return price;
}
public void setPrice(int price) throws LessException, GreatException {
if (price < 200) {
throw new LessException("价格过低!");
} else if (price > 20000) {
throw new GreatException("价格过高!");
} else {
this.price = price;
}
}
}
```
最后是ExceptionTest3类的定义,其中我们在main方法中调用setPrice方法,使用try/catch捕获setPrice方法中抛出的异常:
```java
public class ExceptionTest3 {
public static void main(String[] args) {
Phone phone = new Phone("华为", 1000);
try {
phone.setPrice(50000);
} catch (LessException e) {
System.out.println("价格过低:" + e.getMessage());
} catch (GreatException e) {
System.out.println("价格过高:" + e.getMessage());
}
}
}
```
这样,当我们在main方法中调用setPrice方法时,如果价格不符合要求,则会抛出相应的异常,并被try/catch块捕获和处理。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)