java 异常处理的语句执行

概念

1.try

如果在一个方法内部出现了异常(或者在方法内部调用的其他方法抛出了异常),这个方法将在抛出异常的过程中结束


异常处理理论上有两种基本模型。终止模型和恢复模型。个人理解回复模型类似于中断处理。而java支持终止模型,这种模型中,程序无法返回异常发生的地方继续执行。


要是不希望方法就此结束,可以在方法内设置一个特殊的块来捕获异常,成为try块。

2.catch

对于抛出的异常必须在某处得到处理,异常处理程序以关键字catch表示,紧跟在try后。


3.finally

有一些代码希望无论有没有异常抛出都能够执行,可以在catch后面加finally子句。


4.结构

try{

}catch{

}finally{

}

5.执行顺序

a.抛出异常处理顺序

public class TestException {    
    public static void main(String[] args) {    	
    	TestException testException1 = new TestException();  
    	int i=1;
        try {  
        	i=2;
        	System.out.println("in try");
            testException1.fun();
        	System.out.println("end try");

        } catch (Exception e) {  
            System.out.println("in catch");
        } finally{
        	i=3;
        	System.out.println("in finally");        	
        }         
        System.out.println("the  end  i="+i);
    } 
    
    public  void fun() throws Exception{    	
    	throw new Exception();     	    	
    }
}  

输出结果:

in try
in catch
in finally
the  end  i=3
 
可以看到testException1.fun();抛出异常以后,代码跳出try块转到catch执行异常处理程序,然后继续执行finally程序。最后顺序执行System.out.println("the  end  i="+i);如果没有try块的话,整个方法都会跳出。


b.不抛出异常处理顺序

public class TestException {    
    public static void main(String[] args) {    	
    	TestException testException1 = new TestException();  
    	int i=1;
        try {  
        	i=2;
        	System.out.println("in try");
            //testException1.fun();
        	System.out.println("end try");

        } catch (Exception e) {  
            System.out.println("in catch");
        } finally{
        	i=3;
        	System.out.println("in finally");        	
        }         
        System.out.println("the  end  i="+i);
    } 
    
    public  void fun() throws Exception{    	
    	throw new Exception();     	    	
    }
}  

结果输出:

in try
end try
in finally
the  end  i=3

可以看到不管异常抛不抛出,finally语句都会执行。





  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值