编写Person类,包含人的姓名和年龄;编写自定义异常类IllegalAgeException,当用户输入的年龄小于0的时候,抛出IllegalAgeException异常,为用户友好提示错误信息。 测试类代码如下: public class TestPersonException { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); try { Person p1 = new Person(scanner.next(), scanner.nextInt()); System.out.println(p1.toString()); } catch (IllegalAgeException e) { System.out.println(e.getMessage()); System.out.println("你输入的年龄为" + e.getAge()); } } }
时间: 2024-02-22 15:00:27 浏览: 14
好的,我明白了。这是一个关于Java异常处理的问题,你需要定义一个Person类和一个自定义的异常类IllegalAgeException,并在测试类中使用它们。
下面是代码实现:
```java
// Person类
public class Person {
private String name;
private int age;
public Person(String name, int age) throws IllegalAgeException {
this.name = name;
if (age < 0) {
throw new IllegalAgeException(age);
} else {
this.age = age;
}
}
public String toString() {
return "姓名:" + name + ",年龄:" + age;
}
}
// 自定义异常类IllegalAgeException
public class IllegalAgeException extends Exception {
private int age;
public IllegalAgeException(int age) {
this.age = age;
}
public String getMessage() {
return "年龄不能为负数!";
}
public int getAge() {
return age;
}
}
// 测试类
public class TestPersonException {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
Person p1 = new Person(scanner.next(), scanner.nextInt());
System.out.println(p1.toString());
} catch (IllegalAgeException e) {
System.out.println(e.getMessage());
System.out.println("你输入的年龄为" + e.getAge());
}
}
}
```
当用户输入的年龄小于0时,Person类的构造函数会抛出IllegalAgeException异常,并在测试类中进行捕获和处理,输出友好的错误信息。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)