1.在程序中,可能会遇到JDK提供的任何标准异常类都无法充分描述清楚我们想要表达的问题,这种情况下可以创建自己的异常类,即自定义异常类。
2.自定义异常类只需从Exception类或者它的子类派生一个子类即可。
3.自定义异常类如果继承Exception类,则为受检查异常,必须对其进行处理;如果不想处理,可以让自定义异常类继承运行时异常RuntimeException类。
4.习惯上,自定义异常类应该包含2个构造器:一个是默认的构造器,另一个是带有详细信息的构造器。
自定义异常类继承运行时异常RuntimeException类
package yzy.exception;
public class testInheritRuntimeException {
public static void main(String[] args) {
person p = new person();
p.setAge(-1);
}
}
class person {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
if(age<0) {
//手动抛出异常
throw new illegalAgeException("年龄不能为负数");
}
this.age = age;
}
}
class illegalAgeException extends RuntimeException{
public illegalAgeException() {
}
public illegalAgeException(String mesg) {
super(mesg);
}
}
自定义异常类继承Exception类
package yzy.exception2;
public class testInheritException {
public static void main(String[] args) {
person2 P = new person2();
P.setAge(-1);
}
}
class person2 {
private int age;
public int getAge() {
return age;
}
/*
*1抛出异常
public void setAge(int age) throws illegalAgeException2{
if(age<0) {
throw new illegalAgeException2("年龄不能为负数");
}
this.age = age;
}
*/
//2try-catch
public void setAge(int age){
if(age<0) {
try {
throw new illegalAgeException2("年龄不能为负数");
} catch (illegalAgeException2 e) {
e.printStackTrace();
}
}
this.age = age;
}
}
class illegalAgeException2 extends Exception{
public illegalAgeException2() {
}
public illegalAgeException2(String mesg) {
super(mesg);
}
}