java中trycatchfinally再学习

    xiaoxiao2021-03-25  126

    首先捕获异常。

    java编译器只允许如下三种组合方式:

    ①:try/catch

    ②:try/finally

    ③:try/catch/finally

    当有方法声明throw异常时,则要么向上抛出,要么在catch块捕获处理。

    而catch可能也有多个,具体是从小到大的原则,先捕获小的,依次朝着他父类方向捕获。

    finally语句块,除非发生了无法处理的异常从而中断,否则无论如何都会在return之前执行。

    如下事例:

    public class OuterClass { public static void main(String[] args) { System.out.println(test()); } public static int test(){ int a = 10; try { a = 9/1; return a; } catch (Exception e) { a = 2; return 2; } finally{ a=3; //return a; } } }如上,输出为9.

    易错点1:从finally块,a不是已经赋值为3了,为啥返回还是9?

    因为按值传递过来的值~

    易错点2:

    finally块中如果加了return语句,则编译器会报警告,因为无论怎么走,最后都只会从finally块中返回!

    转载请注明原文地址: https://ju.6miu.com/read-2684.html

    最新回复(0)