定义异常 AgeException
package day08.myexception; /** * 自定义异常 */ public class AgeException extends Exception{ public AgeException(){ } public AgeException(String s){ super(s); } }
在person类中(name,age),setAge方法,如果不符合年龄的条件,抛出自定义的AgeException
package day08.myexception; public class Person { private String name; private int age; public Person() { super(); } public Person(String name, int age) throws AgeException{ super(); this.setName(name); this.setAge(age); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) throws AgeException{ if(age>120 || age<0){ throw new AgeException("年龄条件不符合"); }else{ this.age = age; } } public static void main(String[] args) { try { Person p = new Person("zhangfei",30); System.out.println(p.getName()); } catch (AgeException e) { e.printStackTrace(); } } }
* throws:并没有真正的处理异常,只是骗过编译器。
1) 逐层的上抛异常,直到main方法。如果main中仍没有处理,程序会被异常中断。
2) throws中断了本层的代码。
3) throws运行时异常没有意义
要想积极的处理异常,用try-catch-finally:
try{// 出现1次
// 可能出现异常的代码
}catch(异常对象){// 出现0-N次 多次的时候小的写上面,大的写下面,异常时从上到下逐步的捕获的。
// 捕获到对应异常对象之后所做的处理。
}finally{// 出现0-1次,没有catch时finally一定要有。
// 一定会执行的代码
}
一般都是try-catch-finally处理掉。方法中可以不处理,用throws上抛,最终抛到了main,main方法中禁止用throws上抛异常。意味着main一定要处理。