java 编写一个异常类MyException,再编写一个类Student,该类有一个产生异 常的方法public void speak(int m) throws MyException,要求参数m的值大于1000 时,方法抛出一个MyException对象。最后编写主类,在主类的main方法中用 Student创建一个对象,让该对象调用speak方法。
时间: 2023-12-03 20:46:05 浏览: 63
以下是实现代码:
MyException.java
```java
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
```
Student.java
```java
public class Student {
public void speak(int m) throws MyException {
if (m > 1000) {
throw new MyException("参数m的值大于1000");
}
System.out.println("参数m的值为:" + m);
}
}
```
Main.java
```java
public class Main {
public static void main(String[] args) {
Student student = new Student();
try {
student.speak(500);
student.speak(2000);
} catch (MyException e) {
System.out.println("发生异常:" + e.getMessage());
}
}
}
```
在以上代码中,我们定义了一个异常类 `MyException`,继承自 `Exception` 类。并在 `Student` 类中定义了 `speak` 方法,当参数 `m` 大于 1000 时,抛出 `MyException` 异常。在 `Main` 类中,我们创建了一个 `Student` 对象,并调用其 `speak` 方法。由于可能会抛出异常,我们使用 `try-catch` 块来捕获异常并输出异常信息。
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![apk](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)