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 15:19:37 浏览: 28
下面是代码实现:
```java
class RectangleException extends Exception {
public RectangleException(String message) {
super(message);
}
@Override
public String toString() {
return getMessage();
}
}
class Rectangle {
private int width;
private int height;
public void setHW(int width, int height) throws RectangleException {
if (width <= 0) {
throw new RectangleException("width = " + width + " is not a positive number");
}
if (height <= 0) {
throw new RectangleException("height = " + height + " is not a positive number");
}
this.width = width;
this.height = height;
}
}
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.toString());
}
}
}
```
运行结果为:
```
width = -6 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)