try-catch-finally中finally的使用

一、finally介绍

1.finally是可选的
 
2.finally中声明的是一定会被执行的代码。即使catch中又出现异常了,try中有return语句,catch中有return语句等情况。

二、finally的使用

1.当catch中出现异常

代码如下(示例):

public void test1(){
        try{
            int a = 10;
            int b = 0;
            System.out.println(a / b);
            
        }catch(ArithmeticException e){
            e.printStackTrace();
            //catch中出现异常
            int[] arr = new int[10];
            System.out.println(arr[10]);
            
        }catch(Exception e){
            e.printStackTrace();
        }
//        System.out.println("打印1");
        
        finally{
            System.out.println("打印2");
        }
        
    }

如果catch中出现异常,直接退出此方法,打印1就不能显示,但如果将打印1放在finnally中,即使catch中出现异常,仍然可以打印。

2.try中有return语句

代码如下(示例):

public void testMethod(){
        int num = method();
        System.out.println(num);
    }
    
    //try中有return语句
    public int method(){
        
        try{
            int[] arr = new int[10];
            System.out.println(arr[10]);
            return 1;
        }catch(ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            return 2;
        }finally{
            System.out.println("我一定会被执行");
            return 3;
        }

最终return的结果是3

3.手动进行资源的释放

代码如下(示例):

问题代码:

@Test
	public void test2(){
		try{
			File file = new File("hello.txt");
			FileInputStream fis = new FileInputStream(file);
			
			int data = fis.read();
			while(data != -1){
				System.out.print((char)data);
				data = fis.read();
			}
			
			fis.close();
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	

fis是一个输入输出流,不能被JVM自动回收,用fis.close()手动回收,但如果再close前出现异常,跳到catch语句中,fis.closed()就不能被执行到,所以需要用finally改进

改进:

public void test2(){
		FileInputStream fis = null;
		try {
			File file = new File("hello1.txt");
			fis = new FileInputStream(file);
			
			int data = fis.read();
			while(data != -1){
				System.out.print((char)data);
				data = fis.read();
			}
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(fis != null)
					fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

这样不管出不出现异常,finally中的代码是一定会执行的


总结

像数据库连接、输入输出流、网络编程Socket等资源,JVM是不能自动的回收的,我们需要自己手动的进行资源的释放。此时的资源释放,就需要声明在finally中。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值