Java教程

Java finally

Java finally是用于 执行重要代码(例如关闭连接)的块,流等。
无论是否处理异常,总是执行Java最终块。
Java最终块在try或catch块之后。
java最终
注意: 如果您不处理异常,则在终止程序之前,JVM将执行finally块(如果有)。

为什么使用Java finally

Java中的最后一个块可用于放置"清理"代码,例如关闭文件,关闭连接等。

Java的finally用法

让我们看看可以使用Java finally块的不同情况。

案例1

让我们看一下Java最终示例,其中不会发生 例外
class TestFinallyBlock{
    public static void main(String args[]){
        try{
            int data=25/5;
            System.out.println(data);
        }
        catch(NullPointerException e){
            System.out.println(e);
        }
        finally{
            System.out.println("finally block is always executed");
        }
        System.out.println("rest of the code...");
    }
}
Output:5
finally block is always executed
rest of the code...

案例2

让我们看一下java finally示例,其中发生 异常且未对其进行处理
class TestFinallyBlock1{
    public static void main(String args[]){
        try{
            int data=25/0;
            System.out.println(data);
        }
        catch(NullPointerException e){
            System.out.println(e);
        }
        finally{
            System.out.println("finally block is always executed");
        }
        System.out.println("rest of the code...");
    }
}
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero

案例3

让我们看一下java finally示例,其中发生并处理了 异常
public class TestFinallyBlock2{
    public static void main(String args[]){
        try{
            int data=25/0;
            System.out.println(data);
        }
        catch(ArithmeticException e){
            System.out.println(e);
        }
        finally{
            System.out.println("finally block is always executed");
        }
        System.out.println("rest of the code...");
    }
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
注意: 规则: 对于每个try块,可以有零个或多个catch块,但只有一个finally块。
注意: 如果程序退出(通过调用System.exit()或导致导致进程中止的致命错误),将不会执行finally块。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4