/idea :跟着"任亮"做练习题 22,异常;
打印一个人的正常信息,年龄不能是0-200之间,自定义编译期异常
homework家庭作业/
一:
package cn.tx.homework;
public class ValidDataException extends Exception {
//编译期异常构造器的继承ctrl+o;
public ValidDataException() {
super();
}
public ValidDataException(String message) {
super(message);
}
public ValidDataException(String message, Throwable cause) {
super(message, cause);
}
public ValidDataException(Throwable cause) {
super(cause);
}
protected ValidDataException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
二:
package cn.tx.homework;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
//person p = new person("王勇",29);
//选择点person再点alt+回车键,选第二个
try {
person p = new person("王勇",29);
System.out.println(p);
} catch (ValidDataException e) {
e.printStackTrace();
}
}
}
三:
package cn.tx.homework;
//person:人称
public class person {
private String nema;
private int age;
//建立构造器方法 alt+insert键
public person(String nema, int age) throws ValidDataException {
this.nema = nema;
if (age > 0 && age < 200) {
this.age = age;
}else {
//向上抛快捷键;点下面的ValidDataException再点alt+回车键,选第一个
throw new ValidDataException(“未处理的人的年龄的异常”);
}
}
//把上面2个方法封装
public String getNema() {
return nema;
}
public void setNema(String nema) {
this.nema = nema;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//alt+insert键 选第六个: 下面方法只知道把数值变成字符串,为什么这么写我还没理解透
@Override
public String toString() {
return "person{" +
"nema='" + nema + '\'' +
", age=" + age +
'}';
}
}