异常学习小结

异常学习小结:

  1.所有的异常都是由Throwable继承再来的,下一层分为Error和Exception。

  2.Error描述了java运行时系统的内部错误和资源耗尽错误,如outofmemory

  3.Exception 有两个分支,分为RuntimeException和IOException。

    RuntimeException 一般包含ClassCastException、ArrayIndexOutOfBoundsException、NullPointException异常,和派生于Error类的异常并称为“未检查异常”,其它情况称为“已检查异常”。

  4. 可自己创建异常类,只需要派生于Exception或者是其子类即可。

  5.再次抛出异常与异常链

     可在catch内再次抛出异常

		try {
			throw new Exception();
		} catch (Exception e) {
			Throwable se = new ServletException("出错了~~~");
			se.initCause(e);
			Throwable ee = se.getCause();//可以获得其原始异常,此例throw的就是Exception,所以原始异常也是这个
			System.out.println("ee=" + ee);
			throw se;
			
		}

 6.堆栈跟踪元素

public class ExceptionTest {

	public static void t1(){
		t2();
	}
	
	public static void t2(){
		t3();
	}
	
	public static void t3(){
		Throwable t = new Throwable();
		StackTraceElement[] st = t.getStackTrace();
		for (int i = 0; i < st.length; i++) {
			System.out.println(st[i]);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		t1();
	}

}

 结果:

exception.ExceptionTest.t3(ExceptionTest.java:16)
exception.ExceptionTest.t2(ExceptionTest.java:12)
exception.ExceptionTest.t1(ExceptionTest.java:8)
exception.ExceptionTest.main(ExceptionTest.java:28)

 

   跟踪其getStackTrace所在方法的被调用情况,采用堆栈存储形式,后进先出。

 

 

 

 

你可能感兴趣的:(异常学习小结)