1.异常类RectangleException,toString方法返回异常信息。 2.编写矩形类Rectangle,setHW方法设置宽和高,当宽或高小于等于0,则抛出RectangleException异常。
时间: 2024-01-21 11:17:23 浏览: 25
下面是代码实现:
```java
public class RectangleException extends Exception {
public RectangleException(String message) {
super(message);
}
@Override
public String toString() {
return "RectangleException: " + getMessage();
}
}
public class Rectangle {
private double width;
private double height;
public Rectangle() {
width = 0;
height = 0;
}
public void setHW(double w, double h) throws RectangleException {
if (w <= 0 || h <= 0) {
throw new RectangleException("Width or height cannot be less than or equal to 0.");
}
width = w;
height = h;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
}
```
在这个例子中,我们首先定义了一个自定义的异常类 `RectangleException`,它继承自 `Exception`类,并重写了 `toString()` 方法以返回错误信息。
然后我们定义了一个矩形类 `Rectangle`,它有两个私有变量 `width` 和 `height` 分别表示矩形的宽和高。`setHW()` 方法用于设置矩形的宽和高,如果宽或高小于等于0,则抛出 `RectangleException` 异常。`getWidth()` 和 `getHeight()` 方法分别用于获取矩形的宽和高。