程序员地瓜哥的小屋

Java中try、catch、finally执行顺序

2021-07-08  本文已影响0人  CodingDGSun

try、catch和finally


可以有多个catch块,并且try块后面,只能有0个或1个finally块

public static void main(String[] args) {
    try {
        System.out.println("try...");
    }catch (ArithmeticException e){
        System.out.println("ArithmeticException...");
    }catch (NullPointerException e){
        System.out.println("NullPointerException...");
    }
    finally {
        System.out.println("finally...");
    }
}

//输出结果:
//try...
//finally...

try块后面,如果没有catch块,则后面必须有一个finally

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

//输出结果:
//try...
//finally...

执行代码捕获异常后,进入catch块,try中出现异常代码处后面的代码不会再继续执行

public static void main(String[] args) {
    try {
        System.out.println("try...");
        int a = 0;
        String str = null;
        System.out.println(str.toString());
        a = a / 0;
    } catch (ArithmeticException e) {
        System.out.println("ArithmeticException...");
    } catch (NullPointerException e) {
        System.out.println("NullPointerException...");
    } finally {
        System.out.println("finally...");
    }
}

//输出结果:
//try...
//NullPointerException...
//finally...

当try块中或者catch块中遇到return语句时,先执行完finally里面的代码后,再执行return返回语句。

public static void main(String[] args) {
    try {
        System.out.println("try...");
        return;
    } catch (ArithmeticException e) {
        System.out.println("ArithmeticException...");
    } catch (NullPointerException e) {
        System.out.println("NullPointerException...");
    } finally {
        System.out.println("finally...");
    }
}

//输出结果:
//try...
//finally...
public static void main(String[] args) {
    try {
        System.out.println("try...");
        int a = 0;
        a = a / 0;
    } catch (ArithmeticException e) {
        System.out.println("ArithmeticException...");
        return;
    } catch (NullPointerException e) {
        System.out.println("NullPointerException...");
    } finally {
        System.out.println("finally...");
    }
}

//输出结果:
//try...
//ArithmeticException...
//finally...
上一篇下一篇

猜你喜欢

热点阅读