1.异常类RectangleException,toString方法返回异常信息。 2.编写矩形类Rectangle,setHW方法设置宽和高,当宽或高小于等于0,则抛出RectangleException异常。样例输入 -6 0 样例输出 height = -6 is not a positive number width = 0 is not a positive number
时间: 2024-01-21 07:18:11 浏览: 29
下面是可能的实现代码:
```java
public class RectangleException extends Exception {
public RectangleException(String message) {
super(message);
}
}
public class Rectangle {
private int height;
private int width;
public void setHW(int height, int width) throws RectangleException {
if (height <= 0) {
throw new RectangleException("height = " + height + " is not a positive number");
}
if (width <= 0) {
throw new RectangleException("width = " + width + " is not a positive number");
}
this.height = height;
this.width = width;
}
// other methods
@Override
public String toString() {
return "Rectangle{" +
"height=" + height +
", width=" + width +
'}';
}
}
```
测试代码:
```java
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
try {
rectangle.setHW(-6, 0);
} catch (RectangleException e) {
System.out.println(e.getMessage());
}
}
}
```
输出:
```
height = -6 is not a positive number
width = 0 is not a positive number
```
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)