定义测试类ExcepitonTest,在main方法中随机产生汽车行驶速度speed,并调用measureSpeed(double speed)方法测试是否超速。
时间: 2024-02-01 10:15:58 浏览: 30
以下是代码实现:
```java
import java.util.Random;
public class ExceptionTest {
public static void main(String[] args) {
Random random = new Random();
double speed = random.nextDouble() * 200; // 生成随机速度
try {
measureSpeed(speed);
} catch (SpeedOverLimitException e) {
System.out.println(e.getMessage());
}
}
public static void measureSpeed(double speed) throws SpeedOverLimitException {
final double MAX_SPEED = 120.0; // 最大速度为 120 km/h
if (speed > MAX_SPEED) {
throw new SpeedOverLimitException("您的车速已超过限制!");
} else {
System.out.println("当前车速为:" + speed + " km/h");
}
}
}
class SpeedOverLimitException extends Exception {
public SpeedOverLimitException(String message) {
super(message);
}
}
```
在上面的代码中,我们定义了一个 `ExceptionTest` 类,其中的 `main` 方法生成一个随机速度并调用 `measureSpeed` 方法。如果超速了,则会抛出 `SpeedOverLimitException` 异常,我们在 catch 块中打印异常信息。`measureSpeed` 方法会判断速度是否超过限制,如果超过则会抛出异常,否则会输出当前速度。
注意,我们在 `measureSpeed` 方法上声明了 `throws SpeedOverLimitException`,这是因为这个方法可能会抛出 `SpeedOverLimitException` 异常,所以我们需要在方法声明中进行声明。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)