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

2022-07-27

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

2022-07-27

学习记录:异常处理:

异常处理,出现异常不可忽略。


问题描述

finally中异常覆盖了catch到的异常:

public void show() throws BaseException {
    try {
        Integer.parseInt("Hello");
    } catch (NumberFormatException e1) {
        throw new BaseException(e1);
    } finally {
        try {
            int result = 2 / 0;
        } catch (ArithmeticException e2) {
            throw new BaseException(e2);
        }
    }
}

原因分析:

很明显,当catch到异常之后,还会继续执行finally块代码,由于Java只有一张异常表,所以最后finally块中如果抛出异常,就会覆盖前面所有的异常。

为此,Java7开始,特意在Throwable中增加了一个方法,来解决这个问题:

public final void addSuppressed(Throwable exception)


public void read(String filename) throws IOException {
    FileInputStream input = null;
    IOException readException = null;
    try {
        input = new FileInputStream(filename);
    } catch (IOException ex) {
        readException = ex;
    } finally {
        if(input != null){
            try {
                input.close();
            } catch (IOException ex2) {
                if(readException != null){
                    readException.addSuppressed(ex2);    //注意这里
                }else{
                    readException = ex2;
                }
            }
        }
        if(readException != null){
            throw readException;
        }
    }
}

解决方案:

Java7已经考虑到了,用就好了。而且,Java7 开始提供的 try-with-resource 异常代码块(语法糖),就用到了该特性:

package com.mocha.lambda;
 
import java.io.*;
import java.util.zip.GZIPOutputStream;
 
public class TryResourceTest {
 
    public static void main(String[] args) {
        try (FileInputStream fin = new FileInputStream(new File("input.txt"));
             FileOutputStream fout = new FileOutputStream(new File("out.txt"));
             GZIPOutputStream out = new GZIPOutputStream(fout)) {
            byte[] buffer = new byte[4096];
            int read;
            while ((read = fin.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
        } catch (IOException e) {
            //异常处理 TODO
        }
 
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1030671.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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