java异常处理

一. 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--异常声明

  

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ksuper&

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值