java 异常总结

Throwable万恶之首

1.error继承Throwable:程序终结(硬伤)

2.Exception继承Throwable:

①非检查异常(RuntimeException)Java虚拟机自动抛出自动捕获
     异常类型             例子
1>空指针异常:    String str=null;
                        System.out.println(str.length());

2>数组下标越界:int [] ary={1,2,3}
                        for(int i=0;i<=3;i++)

3>类型转换异常:class Dog extends Animal{
                        }
                        class Cat extends Animal{
                         }
                         public class Test{
                         Animal a1=new Dog();
                         Animal a2=new Cat();
                         Dog d1=(Dog)a1;
                         Dog d2=(Dog)a2;

4>算数异常:       分母为0;

②检查异常:需要手动添加处理语句

1>io异常

2>sql异常

 

3.处理异常:try-catch 和try-catch-finaly

try{
//一些会抛出异常的方法
}catch(Exception e){
//处理该异常的代码块
}
System.out.println("程序结束");
try中的异常出现后,try中方法终止执行,执行catch快语句,然后接着执行catch块后的输出语句:System.out.println("程序结束");

1>出现多个异常时 :调用多个catch块,但是异常顺序要对,即父类异常要在子异常的后面

2>finaly:最终一定要执行的语句,在catch的return语句之后执行(返回调用者之前),最后执行main方法

3>如果try-catch中没有return语句,则会调用try-catch之外的return语句


4.异常抛出:

1.throw:写在方法里面,具体的抛出某个异常的动作

2.throws:写在方法名(参数名)之后,声明将要抛出的异常

5.异常连:新的异常中包含原有异常的所有信息
    public void test1()
   { 
     throw new DrunkException("开车别喝酒!"); 
    }
           public void test2(){
          try
          {
                   test1();
            }catch(DrunkException e)
         {
           RuntimeException newExc=new RuntimeException("hello byebye");
            newExc.initCause(e);//initCause方法设置新异常
           throw newExc;//抛出新异常
           }
         主方法:
         public static void main(String args[])
        {
            ChainTest ct=new ChainTest();
             try{
            ct.test2();
             }catch(Exception e)
            {
             e.printStackTrace();
    }
6.异常总结经验:

1> 处理运行时的异常,采用逻辑去合理规避同时辅助try-catch处理
2> 在多重catch块后面,可以加一个catch(Exception)来处理可能遗漏的异常
3> 对于不确定的代码,也可以加上try-catch,处理潜在的异常

 

posted @ 2016-06-28 19:28  n1苏醒a  阅读(63)  评论(0编辑  收藏  举报