理解try-catch-finally结构

try-catch-finally结构

try {
    // code can throw exceptions
} catch (Exception ex) {
    // exception hanlder
} finally {
    // this block is always executed
}

The interesting point is that, code in the finally block always gets executed regardless of what happens in the try block. That means whether the exceptions throw or not, the Java Virtual Machine always execute code in the finally block. Hence the finally is preferred to clean up resources such as closing files, network connections, database connections and so on.
Let’s see an example program that proves the characteristic of the finally block:

    public static void main(String[] args) {
        try {
            String firstAge = args[0];

            System.out.println("First Argument:" + firstAge);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("There is no argument");
        } finally {
            System.out.println("Finally gets executed");
        }
    }

To understand clearly about the benefit of using finally block, consider the following program that writes some text to a file:

    public static void main(String[] args) {
        FileWriter writer = null;
        try {
            writer = new FileWriter("name.txt");
            writer.write("Hello "); //1
            String name = args[0];  //2
            writer.write(name);     //3
            writer.close();         //4
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Look, the line 4 will not be executed in case the line 2 causes an exception (IndexOutOfBoundsException if no argument is passed). If that happens, the try-catch block exits but the file remains opened as line 4 could not be reached.

  • 不管发不发生异常都需要执行的动作应该写到finally中

  • The finally block can be used with the try block only (the catch block is missing)

  • 只有在try块或catch块中出现对System.exit()的调用时,finally块才不会执行

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值