定义一个年龄异常类AgeException; 定义一个Person类,具有name(姓名)、age(年龄)属性,以及setAge(int age)方法,当给age属性的值不在0-200范围内时抛出年龄异常。
时间: 2023-09-17 13:05:10 浏览: 200
### 回答1:
下面是代码实现:
```java
public class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void setAge(int age) throws AgeException {
if (age < 0 || age > 200) {
throw new AgeException("年龄必须在0-200之间");
} else {
this.age = age;
}
}
}
```
在这里,我们定义了一个年龄异常类`AgeException`,它继承自`Exception`类,用于处理年龄异常。然后我们定义了一个`Person`类,它具有`name`和`age`两个属性,以及`setAge(int age)`方法,当给`age`属性的值不在0-200范围内时抛出年龄异常。在`setAge()`方法中,我们使用了`throw`关键字抛出了一个年龄异常。当`setAge()`方法被调用时,如果传入的年龄不在0-200之间,就会抛出`AgeException`。
### 回答2:
年龄异常类AgeException的定义如下:
```java
public class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}
```
Person类的定义如下:
```java
public class Person {
private String name;
private int age;
public void setAge(int age) throws AgeException {
if (age < 0 || age > 200) {
throw new AgeException("年龄不在合法范围内");
}
this.age = age;
}
}
```
在Person类中,setAge方法会检查传入的年龄是否在合法范围内。如果不在0-200范围内,就会抛出自定义的年龄异常AgeException,并附上相应的错误信息。如果年龄在合法范围内,就会将其赋值给age属性。
使用示例:
```java
public class Main {
public static void main(String[] args) {
Person person = new Person();
try {
person.setAge(25); // 设置合法的年龄
} catch (AgeException e) {
System.out.println("发生年龄异常: " + e.getMessage());
}
try {
person.setAge(-10); // 设置非法的年龄
} catch (AgeException e) {
System.out.println("发生年龄异常: " + e.getMessage());
}
}
}
```
在上述示例中,我们先通过setAge方法设置了一个合法的年龄25,没有抛出异常。然后尝试设置一个非法的年龄-10,这时会抛出AgeException,异常信息为"年龄不在合法范围内",我们会在控制台输出该异常信息。
### 回答3:
以下是实现上述要求代码的示例:
```java
class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}
class Person {
private String name;
private int age;
public void setAge(int age) throws AgeException {
if (age < 0 || age > 200) {
throw new AgeException("年龄应在0-200范围内");
}
this.age = age;
}
// 省略name的getter和setter
// ...
}
// 测试代码
public class Main {
public static void main(String[] args) {
Person person = new Person();
try {
person.setAge(250);
} catch (AgeException e) {
System.out.println(e.getMessage());
}
}
}
```
在上述代码中,AgeException类继承自Exception类,表示一个年龄异常。Person类具有name和age属性,以及setAge方法用于设置年龄。当调用setAge方法时,如果传入的年龄不在0-200范围内,会抛出一个AgeException异常。在测试代码中,我们创建一个Person对象,并尝试将年龄设置为250,由于不在合理范围内,导致AgeException异常被抛出,并输出异常的消息。