• 26.异常


    1.异常概述

     2.JVM处理异常的默认方案

     3.异常处理

     3.1  try ...catch...

     4.Throwable的成员方法

     

        public static void main(String[] args) {
            int[] arr = {1, 2, 3};
            System.out.println("开始");
            try {
                run(arr);
            } catch (ArrayIndexOutOfBoundsException throwable) {
                throwable.printStackTrace();
                /**
                 * java.lang.ArrayIndexOutOfBoundsException: 3
                 *     at throwable.TryCatch.run(TryCatch.java:18)
                 *     at throwable.TryCatch.main(TryCatch.java:11)
                 */
            }
            System.out.println("结束");
        }
    
        public static void run(int[] arr) {
            System.out.println(arr[3]);
        }

    5.编译时异常和运行时异常

     5.Throws处理异常

     6.自定义异常

      举例

    public class ScoreException extends Exception {
        public ScoreException() {
        }
    
        public ScoreException(String message) {
            super(message);
        }
    }
    public class CheckScore {
    
        public void checkScore(int score) throws ScoreException {//由于ScoreException继承自Exception,所以是编译时异常,异常需要进行处理(这里进行抛出处理,由调用者处理
    
            if (score < 0 || score > 100) {//分数不在正常范围之内,抛出异常
                throw new ScoreException("分数异常,分数应该在0-100之间");
            } else {
                System.out.println("分数正常");
            }
    
        }
    
    }
        public static void main(String[] args) {
            Scanner scanner=new Scanner(System.in);
            System.out.println("请输入分数:");
            int i = scanner.nextInt();
            CheckScore checkScore=new CheckScore();
            try {
                checkScore.checkScore(i);
            } catch (ScoreException e) {
                e.printStackTrace();
            }
        }

     Throws和Throw区别

     补充理解throws和try...catch

    throws仅仅是把异常向上抛出,交由调用它的地方去处理,其实并没有实质性的进行处理;

    try...catch会处理异常,不影响程序继续向下执行

  • 相关阅读:
    尚学堂 JAVA DAY12 概念总结
    A new classification algorithm recommendation method based on link prediction
    MLE & MAP
    Performance Measurement
    Stacking
    SVM
    I/O Multiplexing
    Bomb Lab
    ABOUT
    题目集概况 题目列表 提交列表 排名 共 60 分 编程题 (共 60 分) PAT 线上测试赛真题(2020-05-01)
  • 原文地址:https://www.cnblogs.com/luzhanshi/p/13053852.html
Copyright © 2020-2023  润新知