一. finally的意思是:只要你进入try,不管你是怎样离开的,一定要在离开前执行finally的代码。
进入try后离开有三种情况:
(1)没有任何异常发生。这种情况下出来后是不看后面的catch而接着执行下面的代码的,而加了finally后则首先进入finally中来
执行。
(2)try中抛出的异常在try后面的catch中捕捉到并处理完了。这种情况下本来是继续执行下面的代码,现在也先进入finally中来执行。
(3)try中抛出的异常没有在后面的catch中捕捉到,这是try......catch整个就是一个throw,需要继续离开。但加了finally后,将在离开之前先执行finally中的代码。
package 异常处理; class NoWater extends Exception{ } class NoDrinkableWater extends NoWater{ } public class FinallyWorks { static int count=0; public static void main(String[] args) throws NoWater{ while(true){ try{ count++; System.out.println("第"+count+"次:"); if(count==1){ System.out.println("没事"); } else if(count==2){ System.out.println("抛出异常NoDrinksWater"); throw new NoDrinkableWater(); } else if(count==3){ System.out.println("抛出异常NoWater"); throw new NoWater(); } }catch(NoDrinkableWater e){ System.out.println("NoDrinkableWater"); }finally{ System.out.println("在finally中"); if(count==3){ break; } } } } }结果:
二:throw抛出异常
throw new Exception()
package practice3; class NoWater extends Exception{} class NoDrinkableWater extends NoWater{} public class FinallyWorks { static int count=0; public static void main(String[] args) throws NoWater {//异常声明 while(true){ try{ count++; if(count==1){ System.out.println("没事"); } else if(count==2){ System.out.println("抛出异常NoDrinkableWater"); throw new NoDrinkableWater();//抛出异常 } else if(count==3){ System.out.println("抛出异常 NoWater"); throw new NoWater();//抛出异常 } }catch(NoDrinkableWater e){ System.out.println("NoDrinkableWater"); }finally{ System.out.println("在finally中打印"); if(count==3){ break; } } } } }
三:catch匹配
(1)try后面可以跟多个catch,catch的匹配按照书写的顺序,一旦有一个catch匹配到了,执行完了这个catch中的异常处理代码后,后面的catch就不管了
(2)try抛出一个异常,而后面没有任何catch是匹配的,这是整个try.....catch语句变成一个throw
(3)异常的匹配不是精确匹配,它只要满足这个对象是属于那个类的对象就可以了
例如下边的:nodrinkablewater是nowater的子类,子类对象属于父类对象,所以抛出的异常属于nowater类型的,所以可以catch到
package practice4; class nowater extends Exception{}; class nodrinkablewater extends nowater{}; public class water { public static void main(String[] args) { try{ throw new nodrinkablewater(); }catch(nowater e){ System.out.println("nowater"); } } }(4)基本类型Exception,所有异常都是都是这个类的子类
四:关键字 throws--异常声明