无名商城论坛

搜索
查看: 412|回复: 0

[其他技术] 【HC】Java中的异常处理

[复制链接]

1万

主题

1万

帖子

3万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
32464
发表于 2022-5-8 18:41:24 | 显示全部楼层 |阅读模式

Java中的异常处理
在这里插入图片描述示例1:public static void main(String[] args) {    try {        System.out.println(3/0);    } catch (Exception e) {        e.printStackTrace();    } finally {        System.out.println("finally");    }}123456789结果:
在这里插入图片描述示例:Multi-catchpublic static void main(String[] args) {    int d = new Scanner(System.in).nextInt();    try {        System.out.println(3 / d);        new File("G:/dd/aa/ab.txt").createNewFile();    } catch (ArithmeticException e) {        e.printStackTrace();    } catch (IOException e) {        // System.out.println(e.getMessage());        e.printStackTrace();    }    //可以简写为    try {        System.out.println(3 / d);        new File("G:/dd/aa/ab.txt").createNewFile();    } catch (ArithmeticException | IOException e) {        e.printStackTrace();    }}12345678910111213141516171819示例:实现一:抛出异常 public static void main(String[] args) throws IOException {        File file = new File("pom.xml");        FileReader reader = new FileReader(file);        char[] buf = new char[128];        int len = -1;        while((len = reader.read(buf))!= -1){            String res = new String(buf, 0, len);            System.out.println(res);        }        reader.close();    }1234567891011实现二:捕获异常public static void main(String[] args) {    File file = new File("pom.xml");    FileReader reader = null;    try {        reader = new FileReader(file);        char[] buf = new char[128];        int len = -1;        while ((len = reader.read(buf)) != -1) {            String res = new String(buf, 0, len);            System.out.println(res);        }    } catch (IOException e) {        e.printStackTrace();    } finally {        if (reader != null) {            try {                reader.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}12345678910111213141516171819202
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表