7.1 概述
7.2 应用示例
package com.github.demo5;
/**
* @author maxiaoke.com
* @version 1.0
*
*/
public class SexException extends RuntimeException {
public SexException() {}
public SexException(String message) {
super(message);
}
}
package com.github.demo5;
/**
* @author maxiaoke.com
* @version 1.0
*
*/
public class AgeException extends RuntimeException {
public AgeException() {}
public AgeException(String message) {
super(message);
}
}
package com.github.demo5;
/**
* @author maxiaoke.com
* @version 1.0
*
*/
public class Person {
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private int age;
/**
* 性别
*/
private String gender;
public Person() {}
public Person(String name, int age, String gender) {
this.name = name;
if (age < 0 || age > 150) {
throw new AgeException("age必须在0~150之间");
}
this.age = age;
if (!"男".equals(gender) || !"女".equals(gender)) {
throw new SexException("性别必须是男或女");
}
this.gender = gender;
}
@Override
public String toString() {
return "Person{" + "name='" + this.name + '\'' + ", age=" + this.age + ", gender='" + this.gender + '\'' + '}';
}
}
package com.github.demo5;
/**
* @author maxiaoke.com
* @version 1.0
*
*/
public class PersonTest {
public static void main(String[] args) {
Person person = new Person("张三", 180, "呵呵");
System.out.println("person = " + person);
}
}