类与类之间的关系:
tip
--------------------------------
异常:
算术异常
受检异常
throws抛出处理:
方法覆盖中的异常处理:
自定义异常:
异常在开发中的应用:
年龄不合理异:
package wwl.demo01;
public class Test01 {
public static void main(String[] args) {
person p1 = new person();
p1.setName("网五");
try {
p1.setAge(9999);
} catch (AgeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
p1.setGender('女');
System.out.println( p1 );
}
}
package wwl.demo01;
/**
* person类
*
*/
public class person {
private String name;
private int age;
private char gender;
@Override
public String toString() {
return "person [name=" + name + ", age=" + age + ", gender=" + gender + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
// 4.throw所在的方法通过throws声明该异常
public void setAge(int age) throws AgeException{
//对数据进行验证
if(age >= 0 && age < 130) {
this.age = age;
}else {
// 年龄不合法抛出异常
// 3.通过throw抛出一个异常对象
throw new AgeException("年龄越界");
}
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
}
package wwl.demo01;
/**
* 套路:
* 1.定义一个类继承Exception
*
*/
public class AgeException extends Exception {
// 2.一般定义两个构造方法
public AgeException() {
super();
// TODO Auto-generated constructor stub
}
// 有字符串的构造方法,这个字符串参数是异常的信息
public AgeException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
性别不合理异常
package wwl.demo01;
/**
* 自定义性别异常类
*
*/
public class sexexception extends Exception {
public sexexception() {
super();
// TODO Auto-generated constructor stub
}
public sexexception(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
package wwl.demo01;
/**
* person类
*
*/
public class person {
private String name;
private int age;
private String gender;
@Override
public String toString() {
return "person [name=" + name + ", age=" + age + ", gender=" + gender + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
// 4.throw所在的方法通过throws声明该异常
public void setAge(int age) throws AgeException{
//对数据进行验证
if(age >= 0 && age < 130) {
this.age = age;
}else {
// 年龄不合法抛出异常
// 3.通过throw抛出一个异常对象
throw new AgeException("年龄越界");
}
}
public String getGender() {
return gender;
}
public void setGender(String gender) throws sexexception {
if("男".equals(gender) || "女".equals(gender)) {
this.gender = gender;
}else {
//抛出性别不合法异常!
throw new sexexception("性别不合法");
}
}
}
package wwl.demo01;
public class Test01 {
public static void main(String[] args) {
person p1 = new person();
p1.setName("网五");
try {
p1.setAge(9999);
} catch (AgeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p1.setGender("女是");
} catch (sexexception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println( p1 );
}
}