Java的异常处理:try-catch-finally throws throw

Java的异常分为

编译时异常:这类异常在编写时就会出错,必须处理,不然没法编译

    public void method() {
        //此处会弹出编译时异常:FileNotFoundException
        FileInputStream stream = new FileInputStream("Hello.txt");

        int b;
        //此处会弹出编译时异常:IOException
        if ((b = stream.read()) != -1) {
            System.out.println((char)b);
        }
        //此处会弹出编译时异常:IOException
        stream.close();
    }

运行时异常:这类异常编写时是正常的,运行时才会出错

    public static void method1() {
        int[] arr = new int[10];
        //此处异常编写时并不会弹出错误,运行时弹出异常:ArrayIndexOutOfBoundsException
        System.out.println(arr[10]);
    }

  • try-catch-finally:具体处理异常的过程
  • throws:把异常抛给调用该方法的对象来处理
public void method2() {
        //method2方法收到异常后,进行了具体的处理
        try {
            method();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("异常处理完成!");
        }
    }

    //method方法使用throws把异常交给调用该方法的对象处理
    public void method() throws FileNotFoundException, IOException{
        FileInputStream stream = new FileInputStream("Hello.txt");

        int b;
        if ((b = stream.read()) != -1) {
            System.out.println((char)b);
        }
        stream.close();
    }
  • throw:手动抛出一个异常
    public void method4() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学生成绩:");
        double score = scanner.nextDouble();

        if (score >= 0 && score <= 100) {
            System.out.println(score);
        } else {
            //throw手动抛出一个RuntimeException,此处建议使用运行时异常类
            throw new RuntimeException("您输入的成绩有误");
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值