异常分类:异常对象派生于Throwable类的一个实例。Throwable两个分支:Error和Exception
Exception分为运行时异常RuntimeException和其他非运行异常。Error和RuntimeException为未检查异常,其他的异常为已检查异常。
一个方法必须声明所有可能抛出的已检查异常,未检查异常不可控制,应该避免。
子类不能抛超出父类声明异常之外的异常。
抛出异常:Throws Exception ,Throw new Exception()
捕获异常:try/catch/finally
e2.initCause(e1) 将异常e1当作e2的诱饵,抛出e2
import java.io.IOException;
class A{
public void a() throws RuntimeException, IOException{
throw new RuntimeException();
};
}
public class B extends A{
public void a(){
Exception e = new IOException();
RuntimeException re = new RuntimeException();
re.initCause(e);
throw re;
}
public static void main(String [] args){
//A a = new A();
//a.a();
B b = new B();
try{
b.a();
}catch(Exception e){
e.getCause().printStackTrace();
StackTraceElement [] ste = e.getStackTrace();
for(StackTraceElement s:ste){
System.out.println(s);
}
}finally{
System.out.println("done");
}
}
}