栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

《Java 核心技术 卷1》 笔记 第11章 异常、日志、断言和调试(3)Finally子句+跟踪栈

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

《Java 核心技术 卷1》 笔记 第11章 异常、日志、断言和调试(3)Finally子句+跟踪栈

11.2.3 Finally 子句

出现数据库异常,IO链接异常的时候,关闭资源的操作非常重要(不关闭这个资源系统不重启就操作不了)

执行finally的情况:

(1)没有出现异常,执行完 try 块后,执行 finally 子句

(2)抛出一个异常,catch 块执行之后, 执行 finally 子句

(3)代码抛出异常,catch没有捕获,直接执行finally块

Finally 的return会覆盖 try、catch 的 return:

例如:

public class Main {
    public static void main(String[] args) throws Exception {
        Main solution = new Main();

        System.out.println(solution.f(2));
    }

    private int f(int n){
        try{
            return n;
        }finally {
            return 0;
        }
    }

}

public class Main {
    public static void main(String[] args) {
        Main solution = new Main();

        File f = new File("./a.txt");
        FileOutputStream fos = null;
        try{
            if(!f.exists())
                f.createNewFile();
            fos =new FileOutputStream(f);
            fos.write("abc".getBytes());
        }catch (IOException e){
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}

事实上IO的处理有些不友好,资源关闭的时候,也要try…catch,事实上,System.out 也是流,是输出流,这个流close的时候是有进行处理的,看看源码:

加上这一句,编译没有报错

11.2.4 分析堆栈跟踪元素

Throwable t = new Throwable();

StackTraceElement[] frames = t.getStackTrace(0;

For(StackTraceElement frame:frames){}

大概看下,打印的部分包含三大块:

(1)跟踪栈

(2)抑制异常

(3)原因

public class Main {
    public static void main(String[] args) {
        Main solution = new Main();

        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        factorial(n);
    }

    public static int factorial(int n){
        System.out.println("factorial("+n+");");
        Throwable t = new Throwable();
        StackTraceElement[] frames = t.getStackTrace();
        for(StackTraceElement f:frames){
            System.out.println(f);
        }
        int r;
        if(n <= 1) r = 1;
        else r = n* factorial(n-1);
        System.out.println("return "+r);
        return r;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/775158.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号