异常捕捉try catch的使用

异常捕捉try catch的使用

package com.jl.learning.exception;
//try catch的使用
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExceptionTest2 {
    public static void main(String[] args) {
        /*try {
            FileInputStream fis = new FileInputStream("C:\\Users\\Adinistrator\\Java\\新建文本文档.txt");
            System.out.println("以上若出现异常,这里不运行!");
        } catch(FileNotFoundException e){
            System.out.println("文件不存在!");
        }*/
        
        /*try {
            FileInputStream fis = new FileInputStream("C:\\Users\\Adinistrator\\Java\\新建文本文档.txt");
        } catch(IOException e){//抛出FileNotFoundException异常的父类异常IOException,多态!
            System.out.println("文件不存在!");
        }*/

        try {
            //创建输入流
            FileInputStream fis = new FileInputStream("C:\\Users\\Adinistrator\\Java\\新建文本文档.txt");
            //读取文件
            fis.read();//这里read()也会抛出异常
        } catch(FileNotFoundException e){//抛出FileNotFoundException异常的父类异常IOException,多态!
            System.out.println("文件不存在!");
        } catch (IOException e){//抛出异常得从小到大,不能从大到小catch (FileNotFoundException e)和catch (IOException e)不能交换位置
            //因为先捕捉IOException的时候,包含了FileNotFoundException,再处理FileNotFoundException会报错已经处理过FileNotFoundException
            System.out.println("读文件报错了!");
        }

        System.out.println("=========================================");

        try {
            //创建输入流
            FileInputStream fis = new FileInputStream("C:\\Users\\Adinistrator\\Java\\新建文本文档.txt");
            //进行数学运算
            System.out.println(100 / 0);//运行时异常,编写时可以处理也可以不处理
        } catch(FileNotFoundException| ArithmeticException|NullPointerException e){//JDK 8 后允许多个异常同时写,用|隔开
            System.out.println("文件不存在?数学异常?空指针异常?都有可能!");}
        
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值