Think in Java(九):通过异常处理错误

1. finally能做什么?
当要把除内存之外的资源恢复到它们的初始状态时,就要用到finally子句。这种需要清理的资源包括:已经打开的文件或网络连接

2. 子类覆盖父类方法的时候,不能抛出比父类更多的异常


3. 异常处理的一个重要目标是把错误处理的代码同错误发生的地点相分离,这使你能在一段代码中专注于要完成的事情,至于如何处理错误,则放在另一段代码中完成。


4. finally块中避免使用return语句,如果在finally中使用return,会吃掉try catch中的异常信息,屏蔽了错误的发生。

public class TryCatchFinally {
    public static final String test() {
        String t = "";
 
        try {
            t = "try";
            int i = 1/0;
            return t;
        } catch (Exception e) {
            // result = "catch";
            t = "catch";
            return t;
        } finally {
            t = "finally";
            return t;
        }
    }
 
    public static void main(String[] args) {
        System.out.print(TryCatchFinally.test());
    }
 
}
// output:  finally
5. finally块中避免再次抛出异常,否则也会吃掉try catch语句块中的异常。

6. 在try catch中return,在finally中对值的修改是不会生效的:

public class TryCatchFinally {
    public static final String test() {
        String t = "";

        try {
            t = "try";
            return t;
        } catch (Exception e) {
        	t = "catch";
        	return t;
        } finally {
            t = "finally";
        }
    }
 
    public static void main(String[] args) {
        System.out.print(TryCatchFinally.test());
    }
 
}
// output:  try

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值