java try-catch-finally 关键字解析

try-catch-finally

作用

主要是用来捕获一些程序中的异常,例如 NullPointerException、IndexOutOfBoundsException、ArithmeticException等。

try {
	int i = 10 / 0; // throw a ArithmeticException!
} catch (ArithmeticException e) {
	// do something
}

触发机制

1、catch 代码块只有在 try 代码块中抛出相应的异常,或者其异常子类时才会执行。

try {
    int i = 10 / 0; // throw a ArithmeticException!
} catch (NullPointerException e) {
    System.out.println("NullPointerException");
} catch (ArithmeticException e) {
    System.out.println("ArithmeticException");
} catch (Exception e) {
    System.out.println("Exception");
}

执行结果
在这里插入图片描述
2、finally 代码块一定会被执行,不管 try 代码块是否出现异常。

try {
    int i = 10 / 0; // throw a ArithmeticException!
} catch (NullPointerException e) {
    System.out.println("NullPointerException");
} catch (ArithmeticException e) {
    System.out.println("ArithmeticException");
} catch (Exception e) {
    System.out.println("Exception");
} finally {
    System.out.println("finally");
}

执行结果
在这里插入图片描述

注意点

1、try 代码块不可单独存在,必须搭配 catch 代码块或 finally 代码块。

try {
    int i = 10 / 0;
} finally {}
try {
    int i = 10 / 0;
} catch (Exception e) {}

2、笔试题

public class CSDNTest {

    public static void main(String[] args) {
        System.out.println(method());
    }
    
    private static int method() {
        int result;
        try {
            result = 1;
            int i = 10 / 0;
        } catch (Exception e) {
            result = 2;
        } finally {
            result = 3;
        }
        return result;
    }
}

最后执行结果
在这里插入图片描述
如果是以下这段代码呢?

public class CSDNTest {

    public static void main(String[] args) {
        System.out.println(method());
    }

    private static int method() {
        int result;
        try {
            result = 1;
            return result;
        } catch (Exception e) {
            result = 2;
        } finally {
            result = 3;
        }
        return result;
    }
}

执行结果
在这里插入图片描述

JVM 在执行 finally 代码块之前,会将 try-catch 代码块的结果集先暂存起来。

额外

finally 代码块一般是用来释放一些资源的。不过 java7 之后,就引入了 try-with-resources 语法。它可以自动地在语句块执行完后关闭资源。使用这种语法可以避免在 finally 块中显式地关闭资源,从而减少代码的复杂性。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值